我正在从teamtreehouse.com制作一个非常基本的React应用程序,并且不断遇到
“ TypeError:无法读取未定义的属性’onPlayerScoreChange’”
即使我正确绑定了我的功能(我认为)
'onPlayerScoreChange'是Grandparent组件中的一种方法,当用户单击“ +”或“-”按钮以更改玩家得分时执行。
'onPlayerScoreChange'
Grandparent
如果有人可以解释什么地方出了错,那将非常有帮助,因为我认为我是this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this)在曾祖父母的构造函数中进行设置的。
this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this)
父组件:
class App extends React.Component { constructor(props) { super(props); this.onPlayerScoreChange = this.onPlayerScoreChange.bind(this) this.state = { initialPlayers: props.initialPlayers, }; } onPlayerScoreChange(delta, index) { this.setState((prevState, props) => { return {initialPlayers: this.prevState.initialPlayers[index].score += delta} }) } render() { return( <div className = "scoreboard"> <Header title = {this.props.title}/> <div className = "players"> {this.state.initialPlayers.map(function(player, index) { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) })} </div> </div> ) }}
(组件具有默认的标题道具)
子组件:
class Player extends React.Component { render() { return( <div className = "player"> <div className = "player-name"> {this.props.name} </div> <div className = "player-score"> <Counter score = {this.props.score} onChange = {this.props.onScoreChange} index = {this.props.index}/> </div> </div> ) }}
孙子部分:
class Counter extends React.Component { constructor(props) { super(props) this.handleDecrement = this.handleDecrement.bind(this) this.handleIncrement = this.handleIncrement.bind(this) } handleDecrement() { this.props.onChange(-1, this.props.index) } handleIncrement() { this.props.onChange(1, this.props.index) } render() { return( <div className = "counter"> <button className = "counter-action decrement" onClick = {this.handleDecrement}> - </button> <div className = "counter-score"> {this.props.score} </div> <button className = "counter-action increment" onClick = {this.handleIncrement}> + </button> </div> )}}
谢谢!
您尚未绑定要使用的map函数onScoreChange = {this.onPlayerScoreChange},
onScoreChange = {this.onPlayerScoreChange}
您可以使用绑定或箭头功能进行绑定
需要PS绑定,因为map函数的上下文不同于React Component上下文,因此this该函数内部不会引用React Components this,因此您无法访问React Component类的该属性。
this
具有箭头功能:
{this.state.initialPlayers.map((player, index)=> { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) })}
带绑定
{this.state.initialPlayers.map(function(player, index) { return( <Player name = {player.name} score = {player.score} key = {player.id} index = {index} onScoreChange = {this.onPlayerScoreChange} /> ) }.bind(this))}