首页 > 解决方案 > 在 React Native 中显示来自 json 文件的图像

问题描述

我对本机反应并创建一个从 json 获取信息并将其显示为文本和图像的应用程序是新手。

我已将信息存储在 mysql 数据库中,并且我正在使用 php 来获取此信息(如下所示)

<?php
include 'DBConfig.php';

$sql = "SELECT * FROM EventsTable";

$result = $con->query($sql);

if($result->num_rows >0){
    while($row[] = $result->fetch_assoc()) {
        $item = $row;
        $json = json_encode($item);
    }
} else {
    echo "No Results Found!";
}
echo $json;
$con->close();

?>

然后我从 react native 中的文件中获取信息并将其转换为 json。

然后我希望能够以文本形式显示信息并选择图像的文件路径。

这是我的代码。

constructor(props) {
        super(props);
        this.state = {
          isLoading: true, 
          //ImageHolder: ''
        }
      }
      componentDidMount(){
        fetch('http://3b252dcf.ngrok.io/events.php')        
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            isLoading: false,
            dataSource: responseJson,
          }, () => {
            // In this block you can do something with new state.
          });
        })
        .catch((error) => {
          console.error(error);
        });
    }
      ListViewItemSeparator = () => {
        return (
          <View
          style={{
            height: .5,
            width: "100%",
            backgroundColor: "#000",
          }}
        />
        );
      }
      render() {
        if (this.state.isLoading){
          return (
            <View style={{flex: 1, paddingTop: 20}}>
              <ActivityIndicator />
            </View>
          );
        }
        return (
          <View style={styles.MainContainer}>
            <FlatList style={{paddingTop: 30}}
              data={ this.state.dataSource }
              ItemSeparatorComponent = {this.FlatListItemSeparator}
              renderItem={this._renderItem}
            
              />   
          </View>
        );
      }
         _renderItem = ({item}) => {
         {
          return(
              <View style={styles.eventContainer}>
                  <Image source={{url: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>
          );
        }
      }

这是json的格式。

  [{"id":"1","name":"Meeting","eventDate":"Tuesday","eventTime":"7:30pm","eventImage":"require('youth.png')"}}

为了播放图像,我添加了这一行。

 <Image source={{url:item.eventImage}}
                        style={{ width: 100, height: 100, paddingBottom: 10 }}
                />

当我使用 Xcode 在我的 iso 模拟器上运行该应用程序时,图像不显示,并且我收到以下警告。

信息

如何让图像显示

标签: javascriptphpmysqlreact-native

解决方案


尝试这个: <Image source={require('path to file')} ...


推荐阅读