在 React.js 中将 Props 传递给父组件
我们不能使用事件将子组件的 props 发送给其父组件吗React.js?
虽然存在其他解决方案,但它们经常忽略一个基本的问题 观点。父母已经拥有他们传给孩子的道具。因此,孩子们不需要将这些道具发送回父母。
更好的方法
子组件:
子组件是保持简单。
const Child = ({ text, onClick }) => ( <button onclick="{onClick}">{text}</button> );
家长(单身)子级):
利用发送给子级的 prop,父级处理点击事件。
const Parent = ({ childText }) => { const handleClick = (event) => { // Parent already has the child prop. alert(`Child button text: ${childText}`); alert(`Child HTML: ${event.target.outerHTML}`); }; return <child text="{childText}" onclick="{handleClick}"></child>; };
父级(子级列表):
父级管理多个子级,而不会失去对必要信息的访问。
const Parent = ({ childrenData }) => { const handleClick = (childData, event) => { alert( `Child button data: ${childData.childText} - ${childData.childNumber}` ); alert(`Child HTML: ${event.target.outerHTML}`); }; return ( <div> {childrenData.map((childData, index) => ( <child key="{index}" text="{childData.childText}" onclick="{e"> handleClick(childData, e)} /> ))} </child> </div> ); };
此策略尊重封装并减少通过避免依赖孩子的内部结构来耦合。
以上是如何在 React.js 中将 Props 从子级传递给父级?的详细内容。更多信息请关注PHP中文网其他相关文章!