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


在React中,當涉及組件嵌套,在父組件中使用props.children把所有子組件顯示出來。如下:

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

如果想把父組件中的屬性傳給所有的子組件,該怎么做呢?

--使用React.Children幫助方法就可以做到。

比如,把幾個Radio組合起來,合成一個RadioGroup,這就要求所有的Radio具有同樣的name屬性值。可以這樣設計:把Radio看做子組件,RadioGroup看做父組件,name的屬性值在RadioGroup這個父組件中設置。

首先是子組件:

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

然后是父組件,不僅需要把它所有的子組件顯示出來,還需要為每個子組件賦上name屬性和值:

//父組件用,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讓我們對父組件的所有子組件又更靈活的控制。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM