动态渲染React组件

JavaScript

逆天LEY

2020-03-13

在React JSX中,似乎无法执行以下操作:

render: function() {
  return (
    <{this.props.component.slug} className='text'>
      {this.props.component.value}
    </{this.props.component.slug}>
  );
}

我收到一个解析错误:意外令牌{。这不是React可以处理的吗?

我正在设计此组件,以便在内部隐藏的值this.props.component.slug将包含有效的HTML元素(h1,p等)。有什么办法可以使这项工作吗?

第1460篇《动态渲染React组件》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
A逆天猿 2020.03.13

如果您打算注入渲染的实际组件,则可以执行类似的操作,这对于测试非常方便,或者您希望动态注入要渲染的组件的任何原因。

var MyComponentF=function(ChildComponent){
    var MyComponent = React.createClass({
        getInitialState: function () {
            return {
            };
        },
        componentDidMount: function () {
        },
        render: function () {
            return (
                <div className="MyComponent">
                    <ChildComponent></ChildComponent>
                </div>
            );
        }
    });
    return MyComponent;
};

var OtherComponentF=function(){
    var OtherComponent = React.createClass({
        getInitialState: function () {
            return {
            };
        },
        componentDidMount: function () {
        },
        render: function () {
            return (
                <div className="OtherComponent">
                    OtherComponent
                </div>
            );
        }
    });
    return OtherComponent;
};

var AnotherComponentF=function(){
    var AnotherComponent = React.createClass({
        getInitialState: function () {
            return {
            };
        },
        componentDidMount: function () {
        },
        render: function () {
            return (
                <div className="AnotherComponent">
                    AnotherComponent
                </div>
            );
        }
    });
    return AnotherComponent;
};

$(document).ready(function () {
    var appComponent = MyComponentF(OtherComponentF());

    // OR
    var appComponent = MyComponentF(AnotherComponentF());

    // Results will differ depending on injected component.

    ReactDOM.render(React.createElement(appComponent), document.getElementById("app-container"));
});
卡卡西逆天 2020.03.13

编辑:也许您忘了/** @jsx React.DOM */在js开头添加

您可以使用React.DOM

render: function() {
  return React.DOM[this.props.component.slug](null, this.props.component.value);
}

http://jsbin.com/rerehutena/2/edit?html,js,输出

我不是React专家,但是我认为每个组件的开头都应使用特定的标签构建。因此它本身可以提出一个明确的目的。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android