问题
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