Kar*_*ikJ 3 javascript reactjs
我正在使用父子模式下的多个组件的ReactJS.在以下示例中,更新函数从Board组件(父组件)传递到Note组件(子组件).当我执行代码时,我得到Uncaught TypeError: Cannot read property 'update' of undefined错误,我在构造函数中有一个绑定(this).
import React, { Component } from 'react';
import Note from './note';
export default class Board extends Component {
constructor(props) {
super(props);
this.state = {
notes: [
'Call Bill',
'Email list',
'Fix evernote tags'
]
};
this.update = this.update.bind(this);
}
update(newText,i){
alert('update triggered');
var arr = this.state.notes;
arr[i]=newText;
this.setState({notes:arr});
};
eachNote(note,i){
return(
<Note key={i} index={i} onNoteChange={this.update}>{note}</Note>
);
};
render() {
return (
<div className="board">
{ this.state.notes.map(this.eachNote) }
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我将非常感谢您解决此问题的任何帮助.一旦绑定到位,我应该能够在子组件中调用这个父方法吗?
thisin eachNote没有引用Board,它指的是全局范围(在浏览器中window)或者如果你使用strict mode(我认为你使用它)它将是undefined,你需要设置它
{ this.state.notes.map(this.eachNote, this) }
__^^^^___
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2610 次 |
| 最近记录: |