React中props.children和React.Children的區別

在React中,當涉及組件嵌套,在父組件中使用props.children把全部子組件顯示出來。以下:git

function ParentComponent(props){
    return (
        <div>
            {props.children}
        </div>
    )
}

若是想把父組件中的屬性傳給全部的子組件,該怎麼作呢?github

--使用React.Children幫助方法就能夠作到。設計

好比,把幾個Radio組合起來,合成一個RadioGroup,這就要求全部的Radio具備一樣的name屬性值。能夠這樣設計:把Radio看作子組件,RadioGroup看作父組件,name的屬性值在RadioGroup這個父組件中設置。code

首先是子組件:get

//子組件
function RadioOption(props) {
  return (
    <label>
      <input type="radio" value={props.value} name={props.name} />
      {props.label}
    </label>
  )
}

而後是父組件,不只須要把它全部的子組件顯示出來,還須要爲每一個子組件賦上name屬性和值:input

//父組件用,props是指父組件的props
function renderChildren(props) {
    
  //遍歷全部子組件
  return React.Children.map(props.children, child => {
    if (child.type === RadioOption)
      return React.cloneElement(child, {
        //把父組件的props.name賦值給每一個子組件
        name: props.name
      })
    else
      return child
  })
}

//父組件
function RadioGroup(props) {
  return (
    <div>
      {renderChildren(props)}
    </div>
  )
}

function App() {
  return (
    <RadioGroup name="hello">
      <RadioOption label="選項一" value="1" />
      <RadioOption label="選項二" value="2" />
      <RadioOption label="選項三" value="3" />
    </RadioGroup>
  )
}

export default App;

以上,React.Children.map讓咱們對父組件的全部子組件又更靈活的控制。it

項目地址:https://github.com/darrenji/ReactNestedComponentExampleio

相關文章
相關標籤/搜索