无法在子React Native中调用父方法

时间:2020-08-07 14:59:24

标签: react-native

我需要在子组件中调用父级的onPress方法,在此我将导航道具称为调用道具,但是不起作用。我知道有很多类似的主题,但是我发现没有一个案例适合我。

父母:

class Parent extends Component{
    constructor(props){
        super(props);
        this.onPress = this.onPress.bind(this)
        
    }

    onPress() {
        console.log(this.props)
        this.props.navigation.navigate('Play')
    }


    render(){
        return(
            <Child setLevel={this.props.setLevel} navigation = {()=>this.onPress()}/>
             
        )
    }
}

孩子:

class Child extends Component {
    constructor(props){
        super(props);
        this.onPress = this.onPress.bind(this)
    }

    onPress(level) {
        this.props.onPress
        this.props.setLevel(level)
    }

    render(){
        return(
            <View style={styles.container}>
                {levels.map(
                x =>  { return (
                    <View style = {styles.level} key={'level' + x+1}>
                        <TouchableHighlight onPress = {() => this.onPress(x + 1)}>
                            <Text>{x + 1}</Text>
                        </ TouchableHighlight>
                    </View>
                )
                }
            )
    }
            </View>
            
        )
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您有两个错误。

首先,您没有将onPress作为对Child的支持。

第二,您必须像这样在onPress中呼叫Child

this.props.onPress();

因此在Parent中,您需要进行如下更改:

  render() {
    return (
      <Child setLevel={this.props.setLevel} onPress={() => this.onPress()} />
    );
  }

Child中的

  onPress(level) {
    this.props.onPress();
    this.props.setLevel(level);
  }