2017-04-09 132 views
1

我创建的下一个类阵营功能

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').你能说哪里是我的错?

回答

1
<Button onPress={this.addVolume} title="Hi!"/> 

必须

<Button onPress={this.addVolume.bind(this)} title="Hi!"/> 

基本上,这是人们刚刚熟悉反应的常见错误。您需要为该方法提供上下文,因为React不会自动为您执行此操作。


了解更多here

或者,你可以使用下面的代码片段在构造函数

this.addVolume = this.addVolume.bind(this); 
+0

谢谢,现在的作品 –

+1

JSX-没有绑定会怪你! – elmeister

+0

// eslint-disable-line jsx-no-bind 好的,我认罪并提供了替代语法。 – lustoykov