React Native 'require' gotcha? Works for local image file, but not csv file in same directory

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

a React Native newbie here.

Inside my component (inside by App.js file), I'm declaring a variable and setting it to a local CSV file, using require( ).

This errors --->

componentWillMount() {   var csvFilePath = require('./assets/imagesdata.csv');

However, when I set this to the CSV I want, it gives me an error:

Unable to resolve ./assets/imagesdata.csv" from ".//App.js`: The module `./assets/imagesdata.csv` could not be found"

The curious thing is this: if I just sub out the CSV file for another file in the same directory, let's use a .png image file, it works fine with no error -- what gives?

No error (subbed in .png file in the SAME subdirectory as the .csv file that didn't work) --->

componentWillMount() {   var csvFilePath = require('./assets/locationlogo.png');

is there syntax specific to CSV imports that I am unfamiliar with in React?

Here is what my directory looks like, so that you can see that the CSV file in question (imagesdata.csv) is in fact in the same exact subdirectory of assets/ as the .png files that work (locationlogo.png in that example above) .

Thanks!

FYI: I've googled around and tried the solution proposed here (probably not applicable to my case, but i'm desperate: https://github.com/oblador/react-native-vector-icons/issues/626

This suggested running rm ./node_modules/react-native/local-cli/core/__fixtures__/files/package.json before building packager, but I did this, and still didn't solve my weird error).

回答1:

Another React Native newbie here but I know the problem you are facing.

React Native allows you to read images, JSON files and a few other things but not CSV files. To get this CSV file loaded you need to access the FS of the platform(Android/iOS) you are using.

One way to achieve this is to use react-native-fs. To load the CSV file we can use the following code:

var RNFS = require('react-native-fs');  RNFS.readFile("imagesdata.csv")   .then((result) => {     console.log('file contents', result);   })   .catch((err) => {     console.log(err.message, err.code);   });

The path to be used will differ to where the file is located. Kindly refer to the react-native-fs documentation for more information.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!