【问题标题】:How to fix local path from json in React.js?如何修复 React.js 中 json 的本地路径?
【发布时间】:2019-12-23 06:23:59
【问题描述】:

如何修复从 Json 到我的 React 组件渲染的本地路径,

我在整个互联网上搜索了答案,但没有运气:(

NOT WORKING :(
[
    {
        "name": "Apple",
        "id": "001",
        "price": "$995",
        "imgUrl": "./Pictures/219.jpg"
    }
]

WORKING, BUT TURTLE SPEED :/
[
    {
        "name": "Apple",
        "id": "001",
        "price": "$995",
        "imgUrl": "http://www.placekitten.com/200/200"
    }
]

从“反应”导入反应 类产品扩展 React.Component { 构造函数(道具){ 超级(道具) }

render() {
    return (
        <div>
            <img src={this.props.imgUrl}> />
            <p>Name: {this.props.name}</p>
            <p>Id: {this.props.id}</p>
            <p>Price: {this.props.price}</p>
        </div >
    )
}

}


【问题讨论】:

    标签: json reactjs


    【解决方案1】:

    因为我不确定您是否使用 Webpack 来提供图片。我假设你不是,这是从public 目录提供图像的基本方法。

    结构如下:

    public
    |-assets
        |-pictures
           |-219.jpg
    |-src
        |-myImgs.json
        |-App.js
    
    

    json 文件:

      {
            "name": "Apple",
            "id": "001",
            "price": "$995",
            "imgUrl": "./pictures/219.jpg"
      }
    

    App.js

    import React from 'react';
    import myImgs from './myImgs.json'
    
    class App extends React.Component {
    ...
    render() {
      return(
       <>
         <img src={myImgs.imgUrl} alt={myImgs.name} />
       </>
      )
     };
    ...
    };
    
    

    【讨论】:

    • 我正在使用 webpack 来托管服务器。但我想把我所有的图像放在一个文件夹图像中。然后我希望 json 文件中的路径链接到图像文件夹。
    • 我还有一个 Search 组件,其中包含以下内容来呈现我存储在 json 文件中的每一个数据: const product = this.state.Data.filter(search(this.state.search)).map (data => )
    • 这应该仍然有效,但是如果你在 public 目录中有图像,webpack 将不会提供图像。
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2021-03-05
    • 2019-11-11
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多