React: 向现有组件添加道具

我正在想办法用附加道具克隆一个现有的元素。

参考资料:

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

我试图做一些像

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

但是没有用。

我要怎么做?

75885 次浏览

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

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

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.

Of course, there's React.cloneElement() instead, which does a deep copy of another React element and can optionally provide new props.

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

Should work.

If you don't want to use React.cloneElement(), you can use the following snippet:

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