请问react-native 如何编译 字符串模板,有什么模板引擎?

请问react-native 如何编译 字符串模板,有什么模板引擎?
需求是可以直接编译字符串模板
在 运行时可以修改 template 以达到动态组件的目的

function Comp(){
  return compile(template,context)
}
阅读 1.1k
1 个回答

直接用eval或者Function就可以了,不过需要处理一下安全问题,我有一个实现:

const template = 'Hello ${ name }!';
const parser = Sandbox.compile(`\`${ template }\``);
const result = parser({ name: 'Pico' });
console.log(result);

或者最简版本:

function compile(template: string, options?: { throwOnUndefined: boolean }) {
  return (context: any) => {
    const _context = new Proxy(
        context, 
        {
          get: (target, p) => {
            if (p === Symbol.unscopables) {
              return undefined;
            }
            const value = target[p];
            if (options?.throwOnUndefined && value === undefined) {
              throw new ReferenceError(`${ p.toString() } is not defined`);
            }
            return value;
          },
          has: () => true,
        },
      );
    return (new Function('context', `with(context) { return (\`${ template }\`) }`))(_context)
  };
}

const parser = compile('Hello ${ name }!');
const result = parser({ name: 'Pico' });
console.log(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题