Javascript React:向现有组件添加道具

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36750387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:31:18  来源:igfitidea点击:

React: adding props to an existing component

javascriptreactjs

提问by zoopz

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?

我将如何做到这一点?

回答by Salakar

You need to clone the element and add the additional props using React.cloneElemente.g:

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

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

回答by Eugene Ihnatsyeu

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} />;
}

回答by jered

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()代替,这确实的另一个深层副本阵营元素,可以选择提供新的道具。

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

Should work.

应该管用。