React原生-需要未知模块

react native - requiring unknown module

本文关键字:未知 模块 原生 React      更新时间:2023-09-26

我一直在尝试在ListView中加载本地图像文件。

当我硬编码时,它确实工作:

return <Image source={require('./public/image1.png')} style={{width: 60, height: 60}}/>

但是,当我像这样读取图像的路径时,它不起作用:

var path = rowData.thumbnail;
console.log(path); // './public/image1.png'
return <Image source={require(path)} style={{width: 60, height: 60}}/>

或者像这样:

return <Image source={require(rowData.thumbnail)} style={{width: 60, height: 60}}/>

显示错误信息,

需要未知模块"'./public/image1.png'"。如果你确定模块在那里,试着重新启动打包程序或运行"npm install"。

你能给我一个建议从对象中读取路径吗?我附上了完整的代码如下。提前谢谢你。

class MyClass extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    let data = importedData.map(function(d) {
      return {
        thumbnail: "'./public" + d.thumbnail + "'"
      }
    });
    this.state = {
      dataSource: ds.cloneWithRows(data)
    };
  }
  renderRow(rowData) {
    var path = rowData.thumbnail;
    return <View style={{flex: 1, flexDirection: 'row'}}>
      <Image source={require(path)} style={{width: 60, height: 60}}/>
    </View>
  }
  render() {
    return (
      <View style={{paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
        />
      </View>
    );
  }
}

根据React-Native文档,有几种方法可以指定图像的来源:

本地存储:

<Image source={require('./img/favicon.png')}/>

网络:

<Image source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}/>

动态字符串,例如rowData.thumbnail只能用于打包的图像。

如果您的图像加载到图像。iOS上的xcassets和Android上的res/drawable,你可以通过文件名引用它们,如下所示:

<Image source={{uri:'thumbnailFileName'}}/>

或. .

<Image source={{uri:rowData.thumbnail}}/>

你也可以用同样的方式指定占位符。

<Image source={{uri:rowData.thumbnail}} defaultSource={{uri:'placeholder'}}/>

工作演示- https://rnplay.org/apps/tsiGfQ