我正在基于this tutorial.在React中构建应用 我没有使用更新的es2016,而是采用了较旧的方式,因此我遇到了一些问题。我在浏览器中收到此错误:“TypeError:无法读取未定义的属性'props'”。我假设它指向{this.props.onDelete}部分。这是我的Notes.jsx组件代码的片段:
var Notes = React.createClass({
render: function () {
return (
<ul>
{this.props.notes.map(
function(note) {
return (
<li key={note.id}>
<Note
onTheDelete={this.props.onDelete}
task={note.task} />
</li>
);
}
)}
</ul>
);
}
});
这是App.jsx的一个片段,它是父母:
var App = React.createClass({
getInitialState: function () {
return {
notes: [
{
id: uuid.v4(),
task: 'Learn React'
},
{
id: uuid.v4(),
task: 'Do laundry'
}
]
}
},
newNote: function () {
this.setState({
notes: this.state.notes.concat([{
id: uuid.v4(),
task: 'New task'
}])
});
},
deleteNote: function() {
return 'hi';
},
render: function () {
var {notes} = this.state;
return (
<div>
<button onClick={this.newNote}>+</button>
<Notes notes={notes} onDelete={this.deleteNote}/>
</div>
);
}
});
我从deleteNote中删除了实际有用的部分,以确保没有问题。我很难用“this”包裹我的脑袋,以及我在上面提到的教程中绑定的内容。
答案 0 :(得分:5)
this
函数中的 map
与其外的this
不同。
你可以保存this.props.onDelete
并使用它没有道具参考:
render: function () {
var onDelete = this.props.onDelete;
return (
<ul>
{this.props.notes.map(
function(note) {
return (
<li key={note.id}>
<Note
onTheDelete={onDelete}
task={note.task}
/>
</li>
);
}
)}
</ul>
);
}
不相关,但我会将map
函数移动到自己的函数中,避免深度嵌套。
答案 1 :(得分:1)
Dave Newton's answer是完全正确的,但我只想补充一点,如果您使用ES6箭头函数,那么您可以避免必须对此进行额外的引用,以及删除return语句并利用隐式返回语法。
var Notes = React.createClass({
render: function () {
return (
<ul>
{this.props.notes.map(
note => {(
<li key={note.id}>
<Note
onTheDelete={this.props.onDelete}
task={note.task} />
</li>
)}
)}
</ul>
);
}
});