gpt4 book ai didi

javascript - 从子组件 React 传递参数

转载 作者:搜寻专家 更新时间:2023-11-01 04:59:27 25 4
gpt4 key购买 nike

我尝试将参数从子组件传递给父组件。附言如果有人修复此问题,下面的代码片段将不起作用,那将非常棒。

class Parent extends React.Component {

suggestionClick(id) {
console.log(this.props, id); // {props Object} , undefined
}

render(){
return (
<ChildComponent click={this.suggestionClick.bind(this)} />
);
}
}


const ChildComponent = ({ click }) => (
<SubChildComponent id="1" click={() => click()} />
);

const SubChildComponent = ({ click, id }) => (
<div className="subsubcomponent" click={() => click(id)} />
);



ReactDOM.render(
<Parent />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

最佳答案

  1. 不要使用 div 来触发点击。例如,正确的方法是使用按钮
  2. 正确的函数处理程序是 onClick 而不仅仅是点击

class Parent extends React.Component {

suggestionClick(id) {
alert(id);
console.log(this.props, id); // {props Object} , undefined
}

render(){
return (
<ChildComponent click={this.suggestionClick.bind(this)} />
);
}
}


const ChildComponent = ({ click }) => (
<SubChildComponent id="1" click={click} />
);

const SubChildComponent = ({ click, id }) => (
<button className="subsubcomponent" onClick={() => click(id)}>click me</button>
);



ReactDOM.render(
<Parent />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

关于javascript - 从子组件 React 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48265383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com