我是新手,并试图学习这些概念。我正在reactjs上创建演示便笺应用程序。我收到错误
index.js:未捕获的TypeError:无法读取未定义的属性'notes'
我有Board组件和Notes组件如下。
Notes组件:
import React from 'react';
import ReactDOM from 'react-dom';
class Note extends React.Component {
constructor() {
super();
this.state = {editing: false}
this.edit = this.edit.bind(this);
this.save = this.save.bind(this);
}
edit() {
this.setState({editing: true});
}
save() {
this.props.onChange(ReactDOM.findDOMNode(this).value, this.props.index);
this.setState({editing: false});
}
remove() {
this.props.onRemove(this.props.index);
}
renderDisplay() {
return (
<div className='note'>
<p>{this.props.children}</p>
<span>
<button onClick={this.edit} className='btn btn-primary glyphicon glyphicon-pencil'/>
<button onClick={this.remove} className='btn btn-danger glyphicon glyphicon-trash'/>
</span>
</div>
);
}
renderForm() {
return (
<div className='note'>
<textarea className='form-control' defaultValue={this.props.children} ref='newText'></textarea>
<button className='btn btn-success btn-sm glyphicon glyphicon-floppy-disk' onClick={this.save} />
</div>
);
}
render() {
if(this.state.editing) {
return this.renderForm();
} else {
return this.renderDisplay();
}
}
}
export default Note;
和董事会成员:
import React from 'react';
import ReactDOM from 'react-dom';
import Note from './Note';
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
notes: [
'Check emails',
'Log in to jira',
'Fix the issues',
'Logout the system'
]
}
}
update(newText, i) {
console.log(this);
console.log(this.state);
var arr = this.state.notes;
arr[i] = newText;
this.setState({notes: arr});
}
remove(i) {
var arr = this.state.notes;
arr.splice(i, 1);
this.setState({notes: arr});
}
eachNote(note, i) {
return (
<Note key={i}
index={i}
onChange={this.update}
onRemove={this.remove}
>{note}</Note>
);
}
render() {
return (
<div className='board'>
{this.state.notes.map(this.eachNote, this)}
</div>
);
}
}
ReactDOM.render(<Board></Board>, document.getElementById('react-container'));
export default Board;
当我尝试更新音符时,我收到错误,因为音符是使用状态音符变量渲染的,并且我在每个音符上附加了一个属性onChange:{this.update}。在更新中,我正在访问状态变量注释但状态未定义。
任何人都可以给我建议。感谢
答案 0 :(得分:1)
尝试:
onChange={this.update.bind(this)}
而不是:
onChange={this.update}
答案 1 :(得分:0)
为了获得更好的性能,React建议在构造函数中绑定事件处理程序,以便它们仅为每个实例绑定一次。 在此处阅读更多内容:https://facebook.github.io/react/docs/reusable-components.html#no-autobinding