首页 > 解决方案 > 使用 navigation.getParam() React Native Navigation 设置图像名称

问题描述

我在 Stackoverflow 上的第一个问题 :)

我正在使用反应导航。如何通过 navigation.getParam('Country') 的值加载图像?此图像未加载(错误代码 500)

    constructor(props) {
      super(props);
      this.state = { isLoading: true}
      const { navigation } = this.props;
      this.number = navigation.getParam('number');
      this.country = navigation.getParam('country');
    }
    return (
      <View style={bubble.container}>
        <Text>{this.country}</Text>
        <Image source={require('./img/flags/'+ this.country +'.png')} style={{width: 30, height: 30}}/>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <View style={bubble.wrapper}>
                                    <Text selectable>{item.text}</Text>
                                    <View style={bubble.footer}>
                                      <View style={{flex: 1}}>
                                        <Text style={bubble.sender}>{item.sender}</Text>
                                      </View>
                                      <View style={{flex: 1}}>
                                        <Text style={bubble.time}><TimeAgo time={item.datetime} interval={20000}/></Text>
                                      </View>
                                    </View>
                                  </View>}
        />
      </View>
    );

标签: javascriptreact-nativereact-navigation

解决方案


首先,确保你的img在你的JS代码路径中可用,

假设您的 js 代码文件是Country.js,因此,您的文件夹结构应该是:

--Country.js (File)
--img (folder)
  --flags (folder)
    --country.png (an image)

然后,尝试改变你的代码看起来像这样:

render(){
  const {country} = this.props.navigation.state.params
  return (
    <View style={bubble.container}>
      <Text>{country}</Text>
      <Image source={require('./img/flags/'+ country +'.png')} style={{width: 30, height: 30}}/>
      <FlatList
        ..your setting
      />
    </View>
  )
}

不需要声明paramsin constructor,可以声明paramof React NavigationincomponentDidMount()/componentWillMount()/ even in render(){}


推荐阅读