如何在 react-native 中将参数传回 BackHandler 上的 parent 屏幕?

How to pass back param to parent screen on BackHandler in react-native?

"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",

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

TypeError: undefined is not an object (evaluating 'this.props.navigation')

按箭头 header 返回不是问题。但是在智能手机后退按钮本身有这个错误。

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

我试过了,但是 end-up 出现错误:-

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

您缺少对 'this'

的引用

您可以绑定它或像下面这样更改功能

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

当你返回 true 时,你必须自己管理返回,所以第二种方法是首选。

您也可以在那里使用现有的 navigateBack

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