【问题标题】:invalid prop source supplied to image React Native提供给图像 React Native 的无效道具源
【发布时间】:2020-02-19 15:36:42
【问题描述】:

我是原生反应的新手。我有一个以 json 格式存储的图像文件列表,并希望在平面列表中显示它们,但收到以下警告

这是我的json

[{"eventDate": "Tuesday", "eventImage": "require('./youth.png')", "eventTime": "11am - 1pm", "id": "2", "name": "Food Band"}, {"eventDate": "Friday", "eventImage": "require('./youth.png')", "eventTime": "7:30pm", "id": "3", "name": "Youth"}]

这是我的代码。

constructor(props) {
    super(props);
    this.state = {
      isLoading: true, 
      imageHolder: ''
      
    }
  }
  webCall= () => {
       fetch('http://5e26eb00.ngrok.io/events.php', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        }, 
      }).then((response) => response.json())
      .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
        imageHolder: responseJson[0].eventImage
      }, () => {
      });
      console.log(responseJson);
    }).catch((error) => {
    console.error(error);
  });
  }
   componentDidMount(){
 
    this.webCall();
   
   }
  render() {
    if (this.state.isLoading){
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
   <FlatList
   
    data={ this.state.dataSource }
    
    ItemSeparatorComponent = {this.FlatListItemSeparator}

    renderItem={({item}) => 
    
        <View style={{flex:1, flexDirection: 'row', paddingTop: 30, paddingLeft: 10}}>

          <Image source={item.eventImage}

              style={{ width: 100, height: 100, paddingBottom: 10 }}
            />
        
        <View>
              <Text style={styles.rowViewContainer}>{item.name}</Text>
              <Text style={styles.SermonByText}>{item.eventDate} - {item.eventTime}</Text>
          </View>

        </View>
    
      }

    keyExtractor={(item, index) => index.toString()}
    
    />

 </View>
);
}

我的图像本地存储在我的计算机上,我正在使用 Xcode 运行 iOS 模拟器。我不明白为什么我的图片无法显示或我做错了什么。

【问题讨论】:

  • 你是从 react-native 导入图片吗?
  • require('./youth.png') 是 JavaScript 代码。如果从字符串运行,它不会实际执行。
  • 是的,我正在导入它
  • 那我该如何让它工作呢?
  • 您要加载的图像在哪里?它们是您的应用程序源的一部分,还是位于图像服务器的某个位置?

标签: javascript react-native


【解决方案1】:

您正在将&lt;Image&gt;source 设置为值为"require('./youth.png')" 的字符串。这不会像你想象的那样执行。如果您需要 require,由于 React Native 捆绑静态资产的方式,您必须将其作为实际程序的一部分执行。

如果该值来自某些服务,它将不起作用。如果这是您在程序的其他地方定义的某个 JSON 文件或对象,则需要显式执行 require

const img = require('./youth.png');
// or
import img from './youth.png';

<Image source={img} />

如果您的 JSON 来自某个服务,那么您需要另一个服务来托管图像。 React Native 只会捆绑它知道并且可以在“编译”时确定的资产。

【讨论】:

  • 我现在要做的就是确定在哪里托管我的图片
猜你喜欢
  • 2018-10-24
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2021-11-20
  • 2019-08-05
  • 1970-01-01
相关资源
最近更新 更多