React:向现有组件添加道具

React: adding props to an existing component

本文关键字:添加 组件 React      更新时间:2023-09-26

我正试图找出如何用额外的道具克隆现有元素。

供参考:

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

我试着做一些类似的事情

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

但它不起作用。

我该如何做到这一点?

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

const 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!"});

应该有效。