工作生活

React.cloneElement

2019-07-02  本文已影响0人  栗子daisy
React.cloneElement(
  element, 
  [props],
  [...children]
)
参数 说明
element React组件或者原生DOM
[props] 配置当前element的props
[...children] 配置当前element的children,也不能使用this.props.children

React.Children.map
this.props.children

React.Children.map(this.props.children,child=>{
    React.cloneElement(child,{...props},children)
})
function RadioGroup(props) {
  return(
    <div>
      {
        React.Children.map(props.children,child=>{
          return React.cloneElement(child,{name:props.name})
        })
      }
    </div>
  )
}
function RadioItem({children,...rest}) {
  return(
    <label>
      <input type="radio" {...rest}/>{children}
    </label>
  )
}
... 
<RadioGroup name="mvvm">
    <RadioItem value="vue">vue</RadioItem>
    <RadioItem value="react">react</RadioItem>
    <RadioItem value="angular">angular</RadioItem>
</RadioGroup>

<div>
<label><input type="radio" name="mvvm" value="vue">vue</label>
<label><input type="radio" name="mvvm" value="react">react</label>
<label><input type="radio" name="mvvm" value="angular">angular</label>
</div>
上一篇 下一篇

猜你喜欢

热点阅读