[英]How to pass data from child to parent on click of a button in the parent React
我有一个带有父组件和许多子组件的 React 应用程序。 子组件具有经常更改的文本框和其他输入(每个字母类型都会创建状态更改)。
我在孩子中有一个状态来处理这些快速更新(这样父状态不会经常更改并且性能不会降低)。
const ParentComponent = () => { const [globalState, setGlobalState] = useState({}) return <> <ChildComponent value={globalState.value1}/> <ChildComponent value={globalState.value2}/> <ChildComponent value={globalState.value3}/> <ChildComponent value={globalState.value4}/> <ChildComponent value={globalState.value5}/> <ChildComponent value={globalState.value6}/> // I need to be able to fetch the childState on click on this button <button /> </> const ChildOne = ({value}) { const [childValue, setChildValue] = useState(value) // In my actual application, there are multiple text boxes here, so i'm maintaining one state for each input return <input type="text" // this function is triggered everytime a letter is entered onChange={(e)=> setChildValue(e.target.value} /> }
单击父级中的按钮时,我需要将此数据更新为我的父级状态。
我知道我们可以使用 useRef 来实现这一点,但人们说这是一种反模式,应该避免。 我怎样才能以被动的方式做到这一点?
编辑:更多上下文。 我在父级中有几个选项卡,在每个选项卡中都有表单字段,您需要在某个时刻获取选项卡的所有字段的值才能使用该数据发出 POST 请求。 我希望这会有用
我不确定您的应用程序的结构,但要点是从您的子组件修改全局状态。
您可以通过将 setState 函数作为道具从父级传递给子级来做到这一点。
import React from "react";
export default () => {
const [globalState, setGlobalState] = React.useState({
someState: {
value: ""
}
});
return (
<>
{JSON.stringify(globalState)}
<br />
<ChildComponent
value={globalState.someState.value}
setGlobalState={(val) =>
setGlobalState((prev) => ({ ...prev, someState: { value: val } }))
}
/>
</>
);
};
const ChildComponent = ({ setGlobalState, value }) => {
return (
<input
type="text"
value={value}
onChange={(e) => setGlobalState(e.target.value)}
/>
);
};
在管理复杂的表单状态时,有时最好使用诸如 react-hook-form、final-form 或类似性质的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.