简体   繁体   English

将 state 变量和方法传递给 React 中的子组件的更简洁方法?

[英]Cleaner way to pass state variables and methods to child components in React?

Beginner to React, I have multiple state variables: React 初学者,我有多个 state 变量:

function ParentComp(){
      const [firstName, setFirstName] = useState("")
      const [lastName, setLastName] = useState("")
      const [address, setAddress] = useState("")

      return <p>Bonjour</p>
}

Of course I can pass them to the child components like this:当然,我可以像这样将它们传递给子组件:

<ChildComponent firstName = {firstName} setFirstName = {setFirstName}
                lastName = {lastName} setLastName = {setLastName}
                address = {address} setAddress = {setAddress}/>

But I have many more state variables, and actually I want to pass them to the child of the ChildComponent.但是我还有更多的 state 变量,实际上我想将它们传递给 ChildComponent 的子级。 Is there a way to wrap them in a array or object somehow?有没有办法以某种方式将它们包装在数组或 object 中? I googled and found "context api" but I'd like a more beginner friendly solution.我用谷歌搜索并找到了“context api”,但我想要一个对初学者更友好的解决方案。

You can do something like this if you want to keep them as separate states如果您想将它们保持为单独的状态,您可以这样做

<ChildComponent {
  ...{
      firstName, 
      lastName, 
      address, 
      setFirstName, 
      setLastName, 
      setAddress
   }
} />

Otherwise, you coud use useReducer for easier updates to the state and you will get a single object with all states and one update action.否则,您可以使用useReducer更轻松地更新 state,您将获得一个包含所有状态和一个更新操作的 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM