首页 > 解决方案 > React 中从底部组件到顶部组件的 Prop

问题描述

我想在下部组件中获取fullNameandID并将其传递给上部组件并在上部组件中使用它,但我不知道这怎么可能,请帮忙

contacts我的setcontacts状态是道具吗

通过显示map(),我显示所有联系人并为每个联系人放置一个按钮。我希望在单击每个按钮时将同一联系人的 和 发送到顶部 fullName组件idphone

//Top component
const MainContent = ({contacts,setcontacts}) => { 
  return (
    <div>
       <p>{contact.fullName}</p>
       <p>{contact.phone}</p> 
       <p>{contact.id}</p> 

      <Contacts contacts={contacts}/>
    </div>
  );
};
export default MainContent;

//Component down
const Contacts = ({contacts}) => {
  const handleBtn = () => {
   //Send the same contact information as clicked to the component above
  };
  return (
    <div>
      {contacts.map((contact) => (
        <div key={contact.id}>
          <p>{contact.fullName}</p>
          <p>{contact.phone}</p>
          <div>
            <button onClick={handleBtn}>send</button>
          </div>
        </div>
      ))}
    </div>
  );
};

export default Contacts;

标签: reactjs

解决方案


您必须从子组件发送回调以更新父组件中的状态。

在此处查看演示 - https://codesandbox.io/s/simple-child-parent-comp-k2fnn


推荐阅读