我正在尝试显示星级,但出现错误。
错误是:Uncaught TypeError: Cannot read property ‘setState’ of undefined
。
class Foo extends Component {
changeRating( newRating, name ) {
this.setState({
rating: newRating
});
}
render() {
return (
<StarRatings
rating={this.setState.rating}
starRatedColor=“blue”
changeRating={this.changeRating}
numberOfStars={5}
name=‘rating’
starDimension=“20px”
starSpacing=“8px”
/>
);
}
}
有人可以指导我如何解决这个问题吗?
答案 0 :(得分:2)
您的代码中有2个问题:
changeRating
函数未绑定到您的类上下文,从而导致错误。这可以通过箭头功能解决。this.setState
而不是this.state
来获得价值这是解决这两种问题的方法:
class Foo extends Component {
changeRating = (newRating, name) => {
this.setState({
rating: newRating
});
}
render() {
return (
<StarRatings
rating= {this.state.rating}
starRatedColor =“blue”
changeRating = { this.changeRating }
numberOfStars = { 5}
name =‘rating’
starDimension =“20px”
starSpacing =“8px”
/>
);
}
}
我还建议通过在状态中定义默认值或使用null运算符来设置您的评分的默认值:
rating= {this.state.rating || "my default value"}
答案 1 :(得分:0)
class Foo extends Component {
changeRating( newRating, name ) {
this.setState({
rating: newRating
});
}
render() {
return (
<StarRatings
rating={this.setState.rating}
starRatedColor=“blue”
changeRating={this.changeRating}
numberOfStars={5}
name=‘rating’
starDimension=“20px”
starSpacing=“8px”
/>
);
}
}
您尚未将函数绑定到该实例。 因此,使用箭头功能就可以了
changeRating = ( newRating, name ) => {
this.setState({
rating: newRating
});
}
答案 2 :(得分:0)
没有绑定changeRating
函数或箭头函数,因此它无权访问this
。就像另一个答案所说的那样,请使用箭头功能,或者如果您知道性能,请使用bind做:
this.changeRating= this.changeRating.bind(this) //inside your constructor
答案 3 :(得分:-1)
首先定义状态!并使用箭头功能
class Foo extends Component {
state = {
rating: ""
}
changeRating( newRating, name ) {
this.setState({
rating: newRating
});
}
render() {
return (
<StarRatings
rating={this.State.rating} // CHANGE
starRatedColor=“blue”
changeRating={() => this.changeRating} // CHANGE
numberOfStars={5}
name=‘rating’
starDimension=“20px”
starSpacing=“8px”
/>
);
}
}