javascript 在 JSX 中使用 React.cloneElement()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48643323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:09:40  来源:igfitidea点击:

Using React.cloneElement() in JSX

javascriptreactjsjsx

提问by Kiran

I want to know how to use cloneElement syntax in JSX. I read Docs and tried examples but still don't have any clue.

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

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

回答by Shubham Khatri

According to the documentation:

根据文档

Clone and return a new React element using element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

使用 element 作为起点克隆并返回一个新的 React 元素。生成的元素将具有原始元素的 props,新的 props 浅合并。新的孩子将取代现有的孩子。原始元素的 key 和 ref 将被保留。

A valid use case for cloneElement is when you wish to add one/more props to the elements passed a children by the parent.You would simply map over all the children and clone them by adding new props for instance.

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

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

Check a working demo

检查工作演示