gpt4 book ai didi

javascript - 在 React 中导入 JSON 文件

转载 作者:IT老高 更新时间:2023-10-28 12:46:48 28 4
gpt4 key购买 nike

我是 React 新手,我正在尝试从外部文件导入 JSON DATA 变量。我收到以下错误:

Cannot find module "./customData.json"

有人可以帮我吗?如果我在 index.js 中有我的 DATA 变量,但它在外部 JSON 文件中时无效。

index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import customData from './customData.json';
import Profile from './components/profile';
import Hobbies from './components/hobbies';

class App extends Component {
render() {
return (
<div>
<Profile name={this.props.profileData.name}imgUrl={this.props.profileData.imgURL} />
<Hobbies hobbyList={this.props.profileData.hobbyList}/>
</div>
);
}
}

ReactDOM.render(<App profileData={DATA}/>, document.querySelector('.container'));
爱好.js
import React, {Component} from 'react';

var Hobbies = React.createClass({
render: function(){
var hobbies = this.props.hobbyList.map(function(hobby, index){
return (<li key={index}>{hobby}</li>);
});
return (
<div>
<h5>My hobbies:</h5>
<ul>
{hobbies}
</ul>
</div>
);
}
});

export default Hobbies;
profile.js
import React from 'react';

var Profile = React.createClass({
render: function(){
return (
<div>
<h3>{this.props.name}</h3>
<img src={this.props.imgUrl} />
</div>
)
}
});

export default Profile
customData.json
var DATA = {    
name: 'John Smith',
imgURL: 'http://lorempixel.com/100/100/',
hobbyList: ['coding', 'writing', 'skiing']
}

export default DATA

最佳答案

一种好方法(不添加用于代码而非数据和配置的虚假 .js 扩展名)是使用 json-loader 模块。如果你已经使用 create-react-app 搭建项目,模块已经包含,你只需要导入你的 json:

import Profile from './components/profile';

This答案解释更多。

关于javascript - 在 React 中导入 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39686035/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com