React-Native Button onPress setState

时间:2017-06-10 12:45:57

标签: javascript react-native react-native-android

关于这个问题,我已经就stackoverflow上的线程进行了咨询,并观看了video如何制作可点击按钮,但我仍然遇到错误。

这是我的代码

class Button extends Component{
    render(){
        return(
            <View>
                <TouchableOpacity
                    onPress{() => { this.props.onPress() }}>
                    <Text>LOGIN</Text>
                </TouchableOpacity>
            </View>
        )
    }
};

export default class FirstPage extends Component{
    constructor(props) {
        super(props);
        this.state = {clicked: false};
    }

    onTap = () => {
        this.setState({
            clicked: true
        });
        if (this.state.clicked){
            return <SecondPage/>
        }
    }

    render(){
       return(
            <View>
                <Button onPress={() => { this.onTap() }}/>
            </View>
       );
   }
}

但是,我收到此错误

<View>
     <TouchableOpacity
           onPress{() => { this.props.onPress() }}>
                   ^
           <Text>LOGIN</Text>
     </TouchableOpacity>

我可以知道出了什么问题,解决方案是什么?

1 个答案:

答案 0 :(得分:1)

<TouchableOpacity
       onPress={() => { this.props.onPress() }}>

       <Text>LOGIN</Text>
 </TouchableOpacity>
你忘记了“=”

继续;

export default class FirstPage extends Component{
    constructor(props) {
        super(props);
        this.state = {clicked: false};
    }

    onTap = () => {
      alert("点击");
        this.setState({
            clicked: true
        });

    }

    render(){

       return(
            <View>
                {this.state.clicked?
                  <SecondPage />
                  :
                <Button onPress={() =>this.onTap()}/>
              }
            </View>
       );
   }
}
class SecondPage extends Component{
  render(){
    return(
      <View>
        <Text>第二页</Text>
      </View>
    );
  }
}
class Button extends Component{
    render(){
        return(
            <View>
                <TouchableOpacity
                    onPress={() => { this.props.onPress() }}>
                    <Text>LOGIN</Text>
                </TouchableOpacity>
            </View>
        )
    }
};

AppRegistry.registerComponent('RNDemo', () => FirstPage);