嘿,我有一个问题,在反应中删除元素。单击删除按钮后,我在控制台中出错:'script.js:67 Uncaught TypeError:无法在Object上读取未定义的属性'bind'atClick at Object.ReactErrorUtils.invokeGuardedCallback at executeDispatch at Object.executeDispatchesInOrder at executeDispatchesAndRelease at executeDispatchesAndReleaseTopLevel at atAachAccumulated at Object.processEventQueue'的Array.forEach。
var Movie = React.createClass({
propTypes: {
movie: React.PropTypes.object.isRequired,
remove: React.PropTypes.func.isRequired
},
render: function() {
return (
React.createElement('li', {key: this.props.movie.id},
React.createElement(Remove,{remove: this.props.remove, id: this.props.movie.id}),
)
)
}
});
var MovieElem = React.createClass({
propTypes: {
movies: React.PropTypes.array.isRequired
},
getInitialState: function() {
return {
movies
};
},
deleteMovie: function(id) {
this.setState({
movies: this.state.movies.filter(movie => movie.id !== id)
})
},
render: function() {
return (
React.createElement('div', {},
React.createElement('ul', {},
this.state.movies.map(function(movie) {
return React.createElement(Movie, {key: movie.id, movie: movie, remove: () => this.deleteMovie.bind(this)});
})
)
)
}
});
var Remove = React.createClass({
propTypes: {
id: React.PropTypes.number.isRequired,
remove: React.PropTypes.func.isRequired
},
render: function() {
return (
React.createElement('button', {onClick: () => { this.props.remove(this.props.id) }}, 'Delete')
)
}
})
答案 0 :(得分:1)
您需要绑定map函数才能在其中正确引用this
值
render: function() {
return (
React.createElement('div', {},
React.createElement('ul', {},
this.state.movies.map(function(movie) {
return React.createElement(Movie, {key: movie.id, movie: movie, remove: this.deleteMovie});
}.bind(this))
)
)
}