React render component using its name

限于喜欢 提交于 2020-01-12 13:54:25

问题


I am experimenting React.js and it is working really well. I am wondering if it is possible to inject classes to other classes like so:

var Container = React.createClass({
    render: function() {
      <{this.props.implComponent}/>
    }
});

Assuming implComponent has been passed like so:

React.render(
  <Container implComponent="somePredefinedVariable" />,
   document.getElementById('content')
);

This does not work because of a Syntax error. I can easily understand why.

In other words I'd like to inject classes to other classes based on names. Is this possible? How can I do that?


回答1:


You were close. You need to pass the component class it self (not a string), and then because the tag syntax takes a variable already, you get rid of the {}s. Also don't forget to return the node from render.

var Container = React.createClass({
    render: function() {
        return <this.props.implComponent />
    }
});

React.render(
  <Container implComponent={SomePredefinedVariable} />,
   document.getElementById('content')
);

If you want to pass a basic dom component, you'd use a string

This makes sense if you think about the transform result

var Container = React.createClass({displayName: "Container",
    render: function() {
      return React.createElement(this.props.implComponent, null)
    }
});

ReactDOM.render(
  React.createElement(Container, {implComponent: SomePredefinedVariable}),
   document.getElementById('content')
);
ReactDOM.render(
  React.createElement(Container, {implComponent: "div"}),
   document.getElementById('content')
);


来源:https://stackoverflow.com/questions/27926690/react-render-component-using-its-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!