我正在从 teamtreehouse.com 制作一个非常基本的 React 应用程序,我经常遇到
“类型错误:无法读取未定义的属性‘onPlayerScoreChange’”
即使我正确绑定了我的功能(我认为)
'onPlayerScoreChange'
是Grandparent
组件中的一个方法,当用户点击“+”或“-”按钮以更改玩家的分数时执行。
如果有人能解释什么是错的,那将非常有帮助,因为我认为我正在设置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>
)
}}
(组件具有标题的默认props)
子组件:
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>
)}}
谢谢!