如何在React-Native中将参数传递回BackHandler的父屏幕?

时间:2020-10-05 07:02:27

标签: reactjs react-native react-native-android react-navigation react-navigation-v5

"react": "16.13.1",
"react-native": "0.63.2",
"@react-navigation/bottom-tabs": "^5.7.3",
"@react-navigation/compat": "^5.2.5",
"@react-navigation/material-bottom-tabs": "^5.2.15",
"@react-navigation/material-top-tabs": "^5.2.15",
"@react-navigation/native": "^5.7.3",
"@react-navigation/stack": "^5.9.0",

当我在设备上按回时,我想将数据传递回父屏幕。但是我得到了错误:-

TypeError:未定义不是对象(正在评估“ this.props.navigation”)

处理返回箭头标题不是问题。但是在智能手机的后退按钮本身上会出现此错误。

MainItem.js

    onPressShowItem = (item, index) => {
        this.props.navigation.navigate('ItemDetails', { FlatData: this.state.FlatData, FlatIndex: index, returnFromItems: this.returnFromItems });
    }
    returnFromItems = data => {
        console.log('returned');
        this.setState({ data });
    }

ItemDetails.js

class ItemDetails extends PureComponent {
  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }
  /// PART OF ERROR APPEAR
  handleBackButton() {
    this.props.route.params.returnFromItems({ FlatData: this.state.FlatData });
    return true;
  }
  // Handle back on header. No problem here
  navigateBack = () => {
    this.props.navigation.goBack();
    this.props.route.params.returnFromItems({ FlatData: this.state.FlatData });
  };
  render() {
    return (
    const RenderBackAction = () => (
      <TopNavigationAction icon={BackIcon} onPress={this.navigateBack} />
        <TopNavigation title='Item Details' alignment='center' accessoryLeft={RenderBackAction} />
    );
    );
  }
}

我尝试过,但最终出现错误:-

1. this.props.route.params.returnFromItems
2. this.props.navigation.state.params.returnFromItems

1 个答案:

答案 0 :(得分:0)

您缺少对“ this”的引用

您可以将其绑定或更改如下功能

handleBackButton=()=> {
    this.props.route.params.returnFromItems({ FlatData: this.state.FlatData });
    return true;
}

当您返回true时,您将必须自行管理回溯,因此首选第二种方法。

您还可以使用现有的NavigationBack

handleBackButton=()=> {
    this.navigateBack();
    return true;
}