首页 > 解决方案 > 这是将道具从孩子传递给父母的正确方法吗?

问题描述

很多时候,当我想应用适当的封装时,即将表单输入字段数据存储在表单组件中,然后通过我的主要组件中的 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);
  }
}

标签: reactjsreact-propsreact-state

解决方案


父.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>;
}

推荐阅读