React Native Navigation set image name with navigation.getParam()

时间:2018-07-24 10:06:34

标签: javascript react-native react-navigation

My frist question on Stackoverflow :)

I'am using React Navigation. How can i load a image by the value of navigation.getParam('Country')?. This Image isn't loading (error code 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>
    );

2 个答案:

答案 0 :(得分:0)

首先,请确保您的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>
  )
}

无需在params中声明constructor,可以在param中声明React Navigation的{​​{1}}

答案 1 :(得分:0)

我已通过URL加载图片

        <Image source={{uri: 'http://192.168.1.222/img/'+ countryvar + '.png'}} style={{width: 30, height: 30}}/>