繁体   English   中英

'Readonly<{}> & Readonly<{ children?: ReactNode; 类型上不存在属性“导航” }>

[英]Property 'navigation' does not exists on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>

我对本地反应完全陌生。

我有以下组件:

播放列表:

export default class Playlists extends Component {
  playlists = [
    ...
  ];

  render() {
    const {navigation} = this.props.navigation;

    return (
      <FlatList
        data={this.playlists}
        renderItem={({item}) => (
          <TouchableOpacity
            style={styles.item}
            onPress={() => navigation.navigate('PlaylistDetails', item)}>
            <Text style={styles.text}>{item.name}</Text>
          </TouchableOpacity>
        )}
      />
    );
  }
}

播放列表的详细信息:

export default class PlaylistDetails extends Component {
  render() {
    const {navigation} = this.props.navigation;
    var songs: Song[] = navigation.getParam('songs');

    return (
      <View>
        <Text>{navigation.getParam('name')}</Text>
        <FlatList
          data={songs}
          renderItem={({item: song}) => <Text>{song.title}</Text>}
        />
      </View>
    );
  }
}

对于导航:

const screens = {
  Playlists: {
    screen: Playlists,
  },
  PlaylistDetails: {
    screen: PlaylistDetails,
  },
};

const stack = createStackNavigator(screens);

export default createAppContainer(stack);

但是在const { navigation } = this.props.navigation; 我收到错误Property 'navigation' does not exist on type ...

我尝试添加以下代码:

interface Props {
    navigation: any
}

然后添加这个:

export default class PlaylistDetails extends Component<Props> {
    ...
}

这消除了错误,但是当我运行应用程序时,我收到以下错误: TypeError: undefined is not an object (evaluating 'navigation.navigate')

我对原生反应完全陌生,不知道如何解决。 我希望有人可以帮助我。

一切都很好,您正在定义正确的接口。

但是,您应该传播道具,而不是深入 1 级并在道具对象内传播navigation属性。

它应该是这样的:

export default class PlaylistDetails extends Component<Props> {
  render() {

    // edit this: 
    const { navigation } = this.props;
    var songs: Song[] = navigation.getParam('songs');

    return (
      <View>
        <Text>{navigation.getParam('name')}</Text>
        <FlatList
          data={songs}
          renderItem={({item: song}) => <Text>{song.title}</Text>}
        />
      </View>
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM