【问题标题】:React: adding props to an existing componentReact:向现有组件添加道具
【发布时间】:2021-12-12 00:04:52
【问题描述】:

我正在尝试弄清楚如何使用其他道具克隆现有元素。

供参考:

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

我试图做类似的事情

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

但它不起作用。

我将如何做到这一点?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

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

【讨论】:

  • 你能给我推荐一些用例吗?
【解决方案2】:

如果不想使用React.cloneElement(),可以使用如下sn -p:

function AddExtraProps(Component, extraProps) {
    return <Component.type {...Component.props} {...extraProps} />;
}
【解决方案3】:

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

当然,there's React.cloneElement() instead,它对另一个 React 元素进行深度复制,并且可以选择提供新的 props。

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

应该可以。

【讨论】:

  • 一分钟后发布的:)
猜你喜欢
  • 1970-01-01
  • 2018-05-26
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 2019-10-18
相关资源
最近更新 更多