Javascript 动态函数赋值
我是一个新手,在尝试将父函数分配给动态创建的子函数时遇到了麻烦Javascript 动态函数赋值,javascript,reactjs,Javascript,Reactjs,我是一个新手,在尝试将父函数分配给动态创建的子函数时遇到了麻烦 class Row extends React.Component { handleStateChange() { console.log(this); //just for test } render() { let notes = [], categoryId = this.props.rowNo; bonuses.forEach(function (bonus, i) {
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>
)
}
类行扩展React.Component{
handleStateChange(){
console.log(this);//仅用于测试
}
render(){
让notes=[],
categoryId=this.props.rowNo;
奖金。forEach(功能(奖金,i){
设id='cell_'+categoryId.toString()+(i+1.toString();
notes.push();
});
返回(
{notes}
)
}
我发现无法读取未定义的属性“handleStateChange”错误。
我做错了什么?这个内部回调函数的作用域指的是调用对象,而不是react类。所以使用()=>
而不是函数
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)}
/>);
});
handleStateChange(){
console.log(this);//仅用于测试
this.setState({parentState:value})
}
奖金。forEach((奖金,i)=>{
设id='cell_'+categoryId.toString()+(i+1.toString();
notes.push();
});
您的此
指的是组件类中的奖金.forEach(function
函数,而不是此
。An应该可以消除该问题
bonuses.forEach((bonus, i) => {
另一方面,如果您不使用ES6,您可以在函数顶部获取此
的副本,然后在函数内部使用:
render() {
let notes = [],
categoryId = this.props.rowNo
self = this;
...
handleRowStateChange={self.handleStateChange}
但是您还有另一个问题。当您进入handleStateChange
函数时,它也会有自己的this
。您可以使用构造函数解决这个问题:
class Row extends React.Component {
constructor (props) {
super(props);
this.handleStateChange = this.handleStateChange.bind(this);
}
...
非常感谢!我想这是所有情况下的最佳实践?是@Dimitry。你应该这样做。顺便说一下console.log(this)
打印子元素,但我需要更改父元素状态。我该怎么做?检查我更新的答案,让我知道它是否适用于你。对不起,不。this.setState不是函数
谢谢解释!