在 React 中将 setStateof 嵌套对象传递给子对象

我有一个问题,我一直在谷歌搜索,但找不到答案。如果我有一个组件(父),它有一个使用钩子的状态useState和另一个我想将 setState 函数传递给的组件(子),但状态是一个嵌套对象,我该怎么做。例如:


家长:


import React, { useState } from 'react';


import ChildComponent from '../components/ChildComponent


export default function Parent() {

const [state, setState] = useState({name: '', age: '', height: '', eyeColor: ''})

return (

     <h1>Title</h1>

     <ChildComponent state={state} setState={???}/>

);

}


孩子:


import React, { useState } from 'react';


export default function ChildComponent({state, setState}) {


return (

     <label htmlFor='nameInput'>Name:</label>

     <input name='nameInput' value={state.name} onChange={(e) => setState???}/>

);

}

我通常知道状态是否在一个组件中setState({...state, state.name: 'Jane'}),但我不确定我将如何传递这种信息setState。


编辑:我希望ChildComponent setState函数是动态的,这样我可以为每个状态值(名称、年龄、身高、eyeColor)重用该组件 4 次,同一个组件可能会传入一个值来更改更新的值?


慕娘9325324
浏览 108回答 4
4回答

慕田峪4524236

一种方式(在许多可能的方式中):export default function Parent() {&nbsp; &nbsp; const [state, setState] = useState({name: '', age: '', height: '', eyeColor: ''})&nbsp; &nbsp; const change = prop => ({target}) => setState(state => ({...state,[prop]:target.value}));&nbsp; &nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<h1>Title</h1>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<ChildComponent label="Name" value={state['name']} onChange={change('name')}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<ChildComponent label="Age" value={state['age']} onChange={change('age')}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<ChildComponent label="Eye Color" value={state['eyeColor']} onChange={change('eyeColor')}/>&nbsp; &nbsp; &nbsp;);}export default function ChildComponent({label,value,onChange}) {&nbsp; &nbsp;return (&nbsp; &nbsp; &nbsp;<label htmlFor={`${label}Input`}>{label}:</label>&nbsp; &nbsp; &nbsp;<input name={`${label}Input`} value={value} onChange={onChange}/>&nbsp; &nbsp;);}

千巷猫影

您可以使用 的函数形式setState来访问当前状态。setState作为第一个参数传递当前状态:onChange={(e)&nbsp;=>&nbsp;setState(currentState&nbsp;=>&nbsp;({...currentState,&nbsp;name:&nbsp;newName}))}

慕森卡

您可以setState像通过state. 家长:&nbsp;import React, { useState } from 'react';&nbsp;import ChildComponent from '../components/ChildComponent&nbsp;export default function Parent() {&nbsp;const [state, setState] = useState({name: '', age: '', height: '', eyeColor: ''})&nbsp;return (&nbsp; &nbsp; &nbsp;<h1>Title</h1>&nbsp; &nbsp; &nbsp;<ChildComponent state={state} setState={setState}/>&nbsp;);}孩子:&nbsp;import React, { useState } from 'react';&nbsp;export default function ChildComponent({state, setState}) {&nbsp;return (&nbsp; &nbsp; &nbsp;<label htmlFor='nameInput'>Name:</label>&nbsp; &nbsp; &nbsp;<input name='nameInput' value={state.name} onChange={(e) => setState(e.target.value)}/>&nbsp;);&nbsp;}

函数式编程

您可能会受益于利用React.createContext并React.useContext在组件之间传递状态。从文档:在典型的 React 应用程序中,数据通过 props 自上而下(父到子)传递,但这对于应用程序中许多组件所需的某些类型的 props(例如语言环境首选项、UI 主题)来说可能很麻烦。Context 提供了一种在组件之间共享这些值的方法,而无需显式地通过树的每个级别传递 prop。下面是一个示例,说明如何使用上下文在 n 层深的组件之间共享状态。const {  useState,  useEffect,   createContext,  useContext} = React;const ComponentContext = createContext();function Parent() {   const [state, setState] = useState({name: 0, age: 0});  return (     <ComponentContext.Provider value={state}>        <div>Parent</div>        <Child/>        <button             onClick={()=>setState({...state, name: state.name+1})}>                Update Name        </button>        <button             onClick={()=>setState({...state, age: state.age+1})}>                Update Age        </button>    </ComponentContext.Provider>  );}function Child() {   const {name} = useContext(ComponentContext);  return <div>      <div>1st Child: {name}</div>      <Child2/>  </div>;}function Child2() {   const {age} = useContext(ComponentContext);  return <div>2nd Child: {age}</div>;}const rootElement = document.getElementById("root");ReactDOM.render( <Parent /> , rootElement);<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script><div id="root"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript