如何使用 Flatlist 在 React Native 中从父级检索数据?

How do I retrieve data from a parent in react native using Flatlist?

我在 ResultsShowScreen.js 中有一个平面列表,当用户点击平面列表中的项目时,我试图将一些数据传递到子屏幕。

    ResultsShowScreen.js
                        <TouchableOpacity 
                            onPress = {() => navigation.navigate('Audioplayer',  {id: item.id, name:item.name, audio_file: item.audio_file}) } >
                            <Text> {item.name}  ({item.length} min) </Text>
                            <Text> {item.short_desc} </Text>
                            <Text> {item.long_desc} </Text>
                            <Text> Avg Rating: {item.avg_rating}/5  ({item.num_ratings} ratiings) </Text>

                        </TouchableOpacity>

在 AudioplayerScreen.js 中,我目前有以下内容并且可以使用。

    const AudioplayerScreen = ( {navigation} ) => {

        // Get values from previous page
        const name = navigation.getParam('name');
        const id = navigation.getParam('id');
        const audio_file = navigation.getParam('audio_file');

但我正在尝试按照此处的教程 (https://amanhimself.dev/build-an-audio-player-in-react-native) 将组件设置为

格式
    export default class AudioplayerScreen extends React.Component {
        // rest of code here

在 AudioplayerScreen.js 中,如何使用上述方法检索从父级传递的数据?

您可以像 this.props.navigation 一样访问相同的 navigation 道具。 react-navigation 确保在注册屏幕时传递 prop。

编辑

这是一个片段:

export default class AudioplayerScreen extends React.Component {
  constructor(props){
    super(props);
    this.name = props.navigation.getParam('name');
  }
  ...
  // or outside constructor
  return <Button title={this.props.navigation.getParam('name')} ... />
}