[英]React: adding props to an existing component
I'm trying to figure out how to clone an existing element with additional props. 我试图弄清楚如何使用其他道具克隆现有元素。
For reference: 以供参考:
this.mainContent = <Hello message="Hello world!" />
I attempted to do something like 我试图做类似的事情
React.createElement(this.mainContent, Object.assign({},
this.mainContent.props, { anotherMessage: "nice to meet ya!" }));
but it's not working. 但它不起作用。
How would I accomplish this? 我怎么做到这一点?
You need to clone the element and add the additional props using React.cloneElement
eg: 您需要使用
React.cloneElement
克隆元素并添加其他道具,例如:
var clonedElementWithMoreProps = React.cloneElement(
this.mainContent,
{ anotherMessage: "nice to meet ya!" }
);
// now render the new cloned element?
If you don't want to use React.cloneElement()
, you can use the following snippet: 如果您不想使用
React.cloneElement()
,则可以使用以下代码段:
function AddExtraProps(Component, extraProps) {
return <Component.type {...Component.props} {...extraProps} />;
}
React.createElement()
takes either a string or a React class type as its first parameter, so that won't work if you're trying to clone an element. React.createElement()
将字符串或React类类型作为其第一个参数,因此如果您尝试克隆元素,则无法使用。
Of course, there's React.cloneElement()
instead , which does a deep copy of another React element and can optionally provide new props. 当然, 还有
React.cloneElement()
,它可以对另一个React元素进行深度复制,并且可以选择提供新的道具。
var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});
Should work. 应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.