简体   繁体   中英

React Native navigate on button press

I am new to React Native, an I am wanting to navigate to a new page on a button press. I have created my own custom button for reuse between screens.

export default class NormalButton extends Component {

constructor(props) {
    super(props);
}

render() {
    return (
        <TouchableOpacity
            style={styles.button}
            onPress={this.props.onPress}
            >
            <Text style={styles.text}>{this.props.text}</Text>
        </TouchableOpacity>
    );
}
}

I want to call this button in my main class and then navigate to another screen when the button is clicked.

export default class Home extends Component {

static route = {
    navigationBar: {
        title: 'Home',
    }
}

constructor(props) {
    super(props);
}

onTestPress = () => {
    this.props.navigator.push('page2');
}

render() {
    return(
        <NormalButton 
            text="test"
            onPress={this.onTestPress}
        />
    );
}
}

When i do this, I get a warning saying "cannot update during an existing state transition" Also, if I take out the onPress from my Home class and just place it in the NormalButton class, it activates the onPress immediately when the app starts and goes to the next screen

您需要在道具中使用箭头绑定。

onPress={() => this.onTestPress()}

Stack navigator is the easiest way to navigate between pages. Please have a look at a below link.

https://reactnavigation.org/docs/en/stack-navigator.html

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