如何从React Native中具有本地路径的JSON调用图像

时间:2018-05-10 11:41:57

标签: json reactjs react-native jsx prefix

import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
} from 'react-native';
import axios from 'axios';
import CarDetail from '../components/CarDetail';

class CarList extends Component {
state = { cars: [] };

componentDidMount() {
axios.get('https://www.website.com/ajx/home_ajx/lister')
.then(response => this.setState({ cars: response.data.data[0]['S1'] 
}));

//Add an if statement here to notify the user when the request fails
}

renderCars() {
return this.state.cars.map(model => 
  <CarDetail key={model.title} modelprop={model} /> 
);
}

render() {
console.log(this.state);

return (
  <ScrollView>
    {this.renderCars()}
  </ScrollView>
);
}  
}

export default CarList;

JSON文件中的图像路径如下:

&#34; image&#34;:&#34; data / models / peugeot-2008-138twf_600X400_.jpg&#34;,

以下是我在另一个组件中调用图像的地方

const CarDetail = ({ modelprop }) => {
const { image } = modelprop;
return (
<Card>
<CardSection>
<View>
  <Image style={imageStyle} 
  source={{ uri: props.modelprop.image }} 
  />
</View>

我相信我需要在我的Global.js中使用某种前缀,这是我无法找到或弄清楚的。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

大多数情况下,您的代码都有错误:

const CarDetail = ({ modelprop }) => {
  const { image } = modelprop;
  return (
    <View>
      <Image
       style={imageStyle} 
       source={{ uri: image }} 
      />
    </View>
  );
}

如果image类似于data/models/peugeot-2008-138twf_600X400_.jpg,你应该使用`$ {Global.imageUrlPrefix} $ {image}`连接所有。