【问题标题】:Dynamic templates in ReactReact 中的动态模板
【发布时间】:2016-04-28 07:30:23
【问题描述】:

我想创建一个简单的Wizard 组件,它应该尽可能通用。

我想为正文内容注入 2 个参数:template(包含一些逻辑)及其context

export class ParentClass extends React.Component {
    render() {
        let template = `Some text: {this.context.testFunc()}`;
        let context = new TestContext();

        return (
            <Wizard template={template} context={context} />
        );
    }
}

export class TestContext {
    testFunc() {
        return "another text";
    }
}

export class Wizard extends React.Component {
    context: null;

    constructor(props) {
        super(props);

        this.context = this.props.context;
    }

    render() {
        return (
            <div>
                {this.props.template}
            </div>
        );
    }
}

问题是template 中包含的逻辑没有执行(它将所有内容都作为字符串写入Wizard)。

我使用ES2015Babel 进行编译。

【问题讨论】:

    标签: reactjs ecmascript-6 react-jsx jsx


    【解决方案1】:

    当您使用模板文字时,您必须使用 $。

    例如

    `Some text: {this.context.testFunc()}`; 
    

    应该是

    `Some text: ${this.context.testFunc()}`;
    

    另外,我认为你的渲染函数有问题

    render() {
            let template = `Some text: {this.context.testFunc()}`;
            let context = new TestContext();
    
            return (
                <Wizard template={template} context={context} />
            );
        }
    

    应该是

    render() {
        let context = new TestContext();
        let template = `Some text: ${context.testFunc()}`;
    
        return (
            <Wizard template={template} context={context} />
        );
    }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2014-10-01
      • 2014-01-13
      相关资源
      最近更新 更多