React:向现有组件添加props

IT技术 javascript reactjs
2021-04-11 09:06:19

我试图弄清楚如何使用附加props克隆现有元素。

以供参考:

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

我试图做类似的事情

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

但它不起作用。

我将如何做到这一点?

3个回答

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

const ClonedElementWithMoreProps = React.cloneElement(
  this.mainContent, 
  { anotherMessage: "nice to meet ya!" }
);
// now render the new cloned element?
你能给我推荐一些用例吗?
2021-05-28 09:06:19

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

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

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

当然,还有React.cloneElement()代替,这确实的另一个深层副本阵营元素,可以选择提供新的props。

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

应该管用。

一分钟后发布:)
2021-06-15 09:06:19