繁体   English   中英

React:将道具添加到现有组件

[英]React: adding props to an existing component

我试图弄清楚如何使用其他道具克隆现有元素。

以供参考:

this.mainContent = <Hello message="Hello world!" />

我试图做类似的事情

React.createElement(this.mainContent, Object.assign({}, 
   this.mainContent.props, { anotherMessage: "nice to meet ya!" }));

但它不起作用。

我怎么做到这一点?

您需要使用React.cloneElement克隆元素并添加其他道具,例如:

var clonedElementWithMoreProps = React.cloneElement(
    this.mainContent, 
    { anotherMessage: "nice to meet ya!" }
);
// now render the new cloned element?

如果您不想使用React.cloneElement() ,则可以使用以下代码段:

function AddExtraProps(Component, extraProps) {
    return <Component.type {...Component.props} {...extraProps} />;
}

React.createElement()将字符串或React类类型作为其第一个参数,因此如果您尝试克隆元素,则无法使用。

当然, 还有React.cloneElement() ,它可以对另一个React元素进行深度复制,并且可以选择提供新的道具。

var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});

应该管用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM