简体   繁体   中英

React-Native Button onPress setState

I have consulted the threads on stackoverflow regarding this issue and watched this video on how to make a clickable button, but i am still getting errors.

Here is my code

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>
       );
   }
}

However, I get this error

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

May I know what went wrong and what is the solution?

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

       <Text>LOGIN</Text>
 </TouchableOpacity>

you forget "="

continue;

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM