reactjs - React 中从底部组件到顶部组件的 Prop
问题描述
我想在下部组件中获取fullName
andID
并将其传递给上部组件并在上部组件中使用它,但我不知道这怎么可能,请帮忙
contacts
我的setcontacts
状态是道具吗
通过显示map()
,我显示所有联系人并为每个联系人放置一个按钮。我希望在单击每个按钮时将同一联系人的 和 发送到顶部
fullName
组件id
。phone
//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;
解决方案
您必须从子组件发送回调以更新父组件中的状态。
在此处查看演示 - https://codesandbox.io/s/simple-child-parent-comp-k2fnn
推荐阅读
- swift - UserDefaults 问题(将数据转换为数组并返回)
- php - 表单转发器仅 POST 第一个值
- google-cloud-dataflow - 运行数据流模板时指定 --diskSizeGb
- r - dplyr 滞后,滞后数因观察而异
- sql - 通过物化路径查询SQL中的邻接表
- email - Google Sheets Mobile 的自动电子邮件功能
- ios - 按顺序获取 PHAsset
- amazon-kinesis-video-streams - 从单个设备组织多个记录的正确方法是什么:AWS Kinesis 视频流
- google-chrome - 为什么我的 Chrome 扩展程序在我重新启动 Chrome 时停止工作?
- python - 从 DataFrame 中删除行,应用开始日期