reactjs - 这是将道具从孩子传递给父母的正确方法吗?
问题描述
很多时候,当我想应用适当的封装时,即将表单输入字段数据存储在表单组件中,然后通过我的主要组件中的 ajax 调用发送数据,我在其中存储应用程序的主要状态,而不是将所有内容存储在一个单一的组件,我遇到了这样的困境:要么全部写在一个组件中(表单和ajax调用),要么将工作拆分到不同的封装组件,同时通过函数回调传输状态/道具。因此我的问题 - 这是将道具移动到父组件的“正确”方式吗?(在这个例子中,只是为了简单起见——通过父组件记录来自子组件的数据)如果没有,什么是更好的方法?提前致谢!
function Parent() {
function getChildData(data) {
console.log(data);
}
return <Child childData={getChildData} />;
}
function Child(props) {
return <button onClick={sendChildData}>Update Parent's State!</button>;
function sendChildData() {
let data = "Data from child component!";
props.childData(data);
}
}
解决方案
父.jsx
const [childData, setChildData] = useState(null);
const Parent = () => {
const handleData = (data) => {
console.log(data);
setChildData(data);
}
return <Child onHandleData={handleData} />;
}
子.jsx
const Child = (props) => {
const { onHandleData } = props;
return <button onClick={onHandleData("Data from child component!")}>Update Parent's State!</button>;
}
推荐阅读
- matlab - 将 Matlab 函数 (mscript) 转换为 simulink 模型
- python - 将列表字符串列表转换为python中的日期以进行时间序列建模 -
- windows - Windows FTP 命令行客户端不会使用 mget * 下载所有文件
- javascript - JWT-解码需要未定义,jwt解码未定义
- scope - openscad 范围问题 a=a+1 解决方法
- amazon-web-services - 169.254.169.254 是否仅由 AWS EC2 使用?
- python - 如何实现从视图到表单的所有业务逻辑?
- angular - 当我在角度中使用自定义组件时,我在单选框中出现错误
- react-native - “this” undefined inside promise react native
- javascript - ReactJs - 复制组件而不滞后网页