我正在试图弄清楚如何使用其他道具克隆现有元素。
供参考:
this.mainContent = <Hello message="Hello world!" />
我尝试做类似
的事情React.createElement(this.mainContent, Object.assign({},
this.mainContent.props, { anotherMessage: "nice to meet ya!" }));
但它不起作用。
我将如何做到这一点?
答案 0 :(得分:46)
您需要使用React.cloneElement
克隆元素并添加其他道具,例如:
var clonedElementWithMoreProps = React.cloneElement(
this.mainContent,
{ anotherMessage: "nice to meet ya!" }
);
// now render the new cloned element?
答案 1 :(得分:15)
如果您不想使用React.cloneElement()
,则可以使用以下代码段:
function AddExtraProps(Component, extraProps) {
return <Component.type {...Component.props} {...extraProps} />;
}
答案 2 :(得分:6)
React.createElement()
将字符串或React类类型作为其第一个参数,以便在您尝试克隆元素时不会起作用。
当然,there's React.cloneElement()
instead,它会对另一个React元素进行深层复制,并且可以选择提供新的道具。
var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});
应该工作。