【问题标题】:How do I retrieve data from a parent in react native using Flatlist?如何使用 Flatlist 从父母那里检索数据?
【发布时间】:2020-06-19 07:08:38
【问题描述】:

我在 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 中,如何使用上述方法检索从父级传递的数据?

【问题讨论】:

    标签: react-native react-native-flatlist


    【解决方案1】:

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

    编辑

    这是一个看起来像的sn-p:

    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')} ... />
    }
    

    【讨论】:

    • 我尝试执行以下操作,但出现 TransformError SyntaxError export default class AudioplayerScreen extends React.Component { name = this.props.navigation.getParam('name'); console.log(name);
    • 你认为你可以添加一个代码 sn-p 以便我可以看到如何访问'name'吗?
    • 在使用类时,您必须在构造函数中执行此操作。我可以在答案中添加一点 sn-p。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2015-03-03
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多