【问题标题】:Unable to call parent's method in child React Native无法在子 React Native 中调用父方法
【发布时间】:2020-08-07 14:59:24
【问题描述】:

我需要在我的子组件中调用我父母的 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>
            
        )
    }
}

感谢您的帮助!

【问题讨论】:

    标签: react-native


    【解决方案1】:

    你有两个错误。

    首先,您没有将 onPress 作为道具传递给 Child

    其次,您必须像这样在Child 中调用onPress

    this.props.onPress();
    

    所以在Parent 中你可以这样改变它:

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

    Child:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2018-07-20
      • 2023-01-03
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      相关资源
      最近更新 更多