gpt4 book ai didi

javascript - ReactJS 动态函数赋值

转载 作者:行者123 更新时间:2023-11-30 11:39:20 25 4
gpt4 key购买 nike

我是 React 的新手,一直在尝试将父函数分配给动态创建的子函数

class Row extends React.Component {

handleStateChange() {
console.log(this); //just for test
}

render() {
let notes = [],
categoryId = this.props.rowNo;

bonuses.forEach(function (bonus, i) {
let id = 'cell_' + categoryId.toString() + (i + 1).toString();
notes.push(<NoteCell bonus={bonus}
songName={id + '.mp3'}
id={id}
key={id}
// that is the point
handleRowStateChange={this.handleStateChange}
/>);
});

return (
<div className="row clearfix">
{notes}
</div>
)
}

我收到 Cannot read property 'handleStateChange' of undefined 错误。我做错了什么?

最佳答案

回调函数中 this 的范围是指调用对象,而不是 react 类。所以使用 ()=> 而不是 function .

handleStateChange() {
console.log(this); //just for test
this.setState({parentState:value})
}

bonuses.forEach((bonus, i) =>{
let id = 'cell_' + categoryId.toString() + (i + 1).toString();
notes.push(<NoteCell bonus={bonus}
songName={id + '.mp3'}
id={id}
key={id}
// that is the point
handleRowStateChange={this.handleStateChange.bind(this)}
/>);
});

关于javascript - ReactJS 动态函数赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294211/

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