2017-07-17 2 views
0

私はMIがエラー を以下与えるstate.Itの値を変更することで問題を抱えている「未定義は(評価 『) this.setStateを({偽 switchValue}』)関数ではありません」スタックのオーバーフローが解決策ではありません。反応ネイティブの状態値を変更するにはどうすればよいですか?私が検索した</p> <p>:

import React, { Component } from 'react'; 
import { 
    Alert, 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    Switch 
} from 'react-native'; 

export default class AwesomeProject extends Component { 
    constructor(props) { 
    super(props); 
    this.state = {switchValue: true}; 

// Toggle the state every second 

} 
_onPressButton() { 
    this.setState({ 
    switchValue: false 
}); 
} 
render() { 
return (
    <View style={styles.container}> 
    <Text style={styles.welcome}> 
     Welcome to React Native! 
    </Text>  
    <Switch 
     onValueChange={this._onPressButton} 
     value={this.state.switchValue } 
    />  
    </View> 
); 
} 
} 

const styles = StyleSheet.create({ 
container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
}, 
instructions: { 
    textAlign: 'center', 
    color: '#333333', 
    marginBottom: 5, 
}, 

});

AppRegistry.registerComponent('AwesomeProject',() => AwesomeProject); 
+0

あなた '_onPressButton'はこの' 'のようにthis'にアクセスする必要があるため、' 'onValueChange = {this._onPressButton.bind(この)}のように、あなたの関数呼び出しをバインドすることができます.setState({}) ' – Andy

答えて

0

_onPressButton内部thisは、正しい参照を参照していません。その場合、その中にthisその_onPressButtonが実際にボタンを参照しています。これは2通りの方法があります。

<Switch 
     onValueChange={this._onPressButton.bind(this)} 
     value={this.state.switchValue } 
    /> 

それとも

<Switch 
     onValueChange={() => this._onPressButton()} 
     value={this.state.switchValue } 
    /> 
関連する問題