阵营功能
问题描述:
我创建的下一个类阵营功能
export default class WaterCount extends Component {
static defaultProps = {};
state = {
currentVolume: 0
};
constructor(props) {
super(props);
}
render() {
return (
{/*Start of buttons container*/}
<View style={styles.buttonsContainer}>
<Button onPress={() => {
this.setState({
currentVolume: this.state.currentVolume + 10
}, function() {
alert(this.state.currentVolume);
});
}} title="Hi!"/>
</View>
}
}
如果我例如,在为按钮定义功能类似上面,一切工作正常。
但是,如果我用这种方式做同样的事情:
export default class WaterCount extends Component {
static defaultProps = {};
state = {
currentVolume: 0
};
constructor(props) {
super(props);
}
render() {
return (
{/*Start of buttons container*/}
<View style={styles.buttonsContainer}>
<Button onPress={this.addVolume} title="Hi!"/>
</View>
);
}
addVolume() {
this.setState({
currentVolume: this.state.currentVolume + 10
}, function() {
alert(this.state.currentVolume);
});
}
}
其放到我的error : undefined is not an object(evaluating 'this.state.currentVolume').
你能说哪里是我的错?
答
<Button onPress={this.addVolume} title="Hi!"/>
必须
<Button onPress={this.addVolume.bind(this)} title="Hi!"/>
基本上,这是人们刚刚熟悉反应的常见错误。您需要为该方法提供上下文,因为React不会自动为您执行此操作。
了解更多here。
或者,你可以使用下面的代码片段在构造函数
this.addVolume = this.addVolume.bind(this);
谢谢,现在的作品 –
JSX-没有绑定会怪你! – elmeister
// eslint-disable-line jsx-no-bind 好的,我认罪并提供了替代语法。 – lustoykov