【问题标题】:Using React.cloneElement() in JSX在 JSX 中使用 React.cloneElement()
【发布时间】:2018-07-16 12:49:15
【问题描述】:

我想知道如何在 JSX 中使用 cloneElement 语法。我阅读了文档并尝试了示例,但仍然没有任何线索。

class ABC extends React.Component {
  constructor(props){
    super(props)
}
render() {
  return(
  <div>
    {React.cloneElement()}
  </div>
  )
}
}

【问题讨论】:

标签: javascript reactjs jsx


【解决方案1】:

根据documentation

使用 element 作为起始克隆并返回一个新的 React 元素 观点。结果元素将具有原始元素的道具 随着新道具的浅浅融合。新的孩子将取代 现有的孩子。来自原始元素的 key 和 ref 将是 保存。

cloneElement 的一个有效用例是当您希望向父级传递给子级的元素添加一个/多个道具时。您只需映射所有子级并通过添加新道具来克隆它们。

return (
  <div style={styles}>
    {React.Children.map(children, child => {
      console.log(child);
      return React.cloneElement(child, {newProp}, null);
    })}
  </div>
)

检查 working demo

【讨论】:

  • 您能否解释一下您在React.Children.map 中获得child 的位置?
  • 在上面的例子中children来自props.childrenchild 是传递给箭头函数的参数。在 ES5 中:jsx {React.Children.map(children, function(child){ console.log(child); return React.cloneElement(child, {newProp}, null); })} reactjs.org/docs/react-api.html#reactchildrenmap
猜你喜欢
  • 2019-07-03
  • 2016-07-30
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-22
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
相关资源
最近更新 更多