【问题标题】:Using a image path in a JSON object to dynamically render image in component使用 JSON 对象中的图像路径在组件中动态渲染图像
【发布时间】:2019-06-29 23:04:17
【问题描述】:

我遇到的问题似乎与在 React 中处理 JSON 对象的其他问题“相似”,尽管我似乎无法翻译这些答案。我正在 React(不是 React Native)中创建一个小游戏。我可以调用我的 JSON 对象并拉取文本,但是,在拉取图像路径时,它不会呈现。要了解这个游戏(HTML/JS 格式)的基本概念,请联系look at this link for the overall functionality

这是问题所在,我有一组基于父组件 (GameLogic.js) 中状态的动态渲染对象。然后我将状态传递给曾曾孙元素,它将在其中渲染两张照片。这些照片路径存储在本地 JSON 文件中(我可以在此级别的 console.log 中从 characters.json 文件中读取字符串)。虽然它可以读取路径(通过 console.log),但它不会渲染这些图像。只要我没有将一条长的动态路径串在一起,我就能够渲染这些图像。

这是文件结构:

-components folder
|-GameLogic.js (parent element that handles the render)
|-Bandersnatch.js (child element)
|-NewComponents folder
  |-ImageContainer.js (grandChild element)
  |-ImageSquare.js (great grandChild element)
-images folder
  |-snatch_images folder (yes... I know how bad this sounds...)
    |-escape_snatch.png
    |-The rest of the images (there are about 20)
 -characters.json
 -App.js

JSON 示例:我需要 Array[0].scene[0].choiceOneImg 的文件路径

[

{
    "name": "Giraffe",
    "alive": true,
    "active": true,
    "staticImg": "images/characters/static/static_giraffe.png",
    "animatedImg": "images/characters/animated/animated_giraffe.png",
    "cagedImg": "images/characters/caged/caged_giraffe.png",
    "scene": [
        {
            "used": false,
            "backgroundImg": "images/BG_images/zooBG.png",
            "question": "........." ,
            "answerTrue": ".......",
            "answerFalse": ".......",
            "choiceOne": "RUN FOR IT!",
            "choiceTwo": "Stay loyal",
            "choiceOneImg": "../images/snatch_images/escape_snatch.png",
            "choiceTwoImg": "images/snatch_images/stay_snatch.png",
            "incorrectResult": 0,
            "correctAnswer": "choiceOne",
            "correct": true
        },

这里是从不断变化的状态传递 currentCharacter、sceneLocation 的 Parent,GameLogic.js:

import React, { Component } from "react";
import Snatch from "./Bandersnatch";
import characters from "../characters.json";

class GameLogic extends Component {

state ={
    unlockedCharacters : 0,
    currentCharacter : 0,
    sceneLocation : 0,
    points : 0,
    showCaracterSelect: true,
    showMessage: false,
    showSnatch: false,
    showCanvas: false,

}

componentDidMount() {

}


render() {
    return (
        <Snatch 
            sceneLocation = {this.state.sceneLocation}
            currentCharacter = {this.state.currentCharacter}
            choiceOneAlt = "ChoiceOne"
            choiceOneImg = {characters[this.state.currentCharacter].scene[this.state.sceneLocation].choiceOneImg}
            choiceTwoAlt = "ChoiceTwo"
            choiceTwoImg = {characters[this.state.currentCharacter].scene[this.state.sceneLocation].choiceTwoImg}
        />
    )
}
}

 export default GameLogic;

然后将其传递给子组件 Bandersnatch.js:

import React, { Component } from "react";
import characters from "../characters.json";
import { HeaderH2, ImageContainer, ImageSquare, ImageText, ProgressBar, Timer } from "./NewComponents/AllComponents";

const Snatch = (props) => {
    return (
        <>
            <title>Decision Time</title>
            <div className="w3-container">
                <div className="container">
                    <HeaderH2 text="What Would You Like To Do?" />

                    <div className="row">
                        <ImageContainer
                            sceneLocation = {props.sceneLocation}
                            currentCharacter = {props.currentCharacter}
                            choiceOneAlt = {props.choiceOneAlt}
                            choiceOneImg = {props.choiceOneImg}
                            choiceTwoAlt = {props.choiceTwoAlt}
                            choiceTwoImg = {props.choiceTwoImg}
                        />
                        {/* <ProgressBar /> */}
                        {/* <ImageText 
                            sceneLocation = {props.sceneLocation}
                            currentCharacter = {props.currentCharacter}
                        /> */}
                    </div>

                </div>
            </div>
        </>
    );

 }

 export default Snatch;

然后将其传递给 ImageContainer:

import React, { Component } from "react";
import ImageSquare from "./ImageSquare";
import characterObject from "../../characters.json";

const ImageContainer = (props) => {
    return (
        <>
            <div className="col-md-6 optionOneclassName">
                <ImageSquare
                    imgsrc={props.choiceOneImg}
                    altText={props.choiceOneAlt}
                />
            </div>
            <div className="col-md-6 optionTwoclassName">
                <ImageSquare
                    imgsrc={props.choiceTwoImg}
                    altText={props.choiceTwoAlt}
                />
            </div>
        </>
    )
 };

 export default ImageContainer;

最后在ImageSquare.js中接受:

import React from "react";

const ImageSquare = (props) => { // passing in the img src
 return (

    <img src={props.imgsrc} alt={props.altText} height="600" width="600" />
   )
};

export default ImageSquare;

非常感谢您的帮助!我不确定是否更容易,but the repo is here

【问题讨论】:

    标签: json reactjs nested react-props nested-object


    【解决方案1】:

    使用 require 加载图像。直接将路径传递给 img 是行不通的。您需要导入或需要加载图像

    你需要在路径前添加../

    改变

       import React from "react";
       const ImageSquare = (props) => { // passing in the img src
         return (
             <img src={props.imgsrc} alt={props.altText} height="600" width="600" />
         )
      };
    
     export default ImageSquare;
    

        import React from "react";
        const ImageSquare = (props) => { // passing in the img src
         const path = "../"+props.imgsrc;
          return (
            <img src={require(path)} alt={props.altText} height="600" width="600" />
           )
     };
    
      export default ImageSquare;
    

    【讨论】:

    • 所以这个变化是在它看起来的曾孙组件(ImageSquare.js)中。从 JSON 对象创建图像路径时,实际呈现的是哪个文件,APP.js、Parent、Child、GrandChild 还是 Great GrandChild?我试过了:“choiceOneImg”:“../../images/snatch_images/escape_snatch.png”、“choiceOneImg”:“../images/snatch_images/escape_snatch.png”和“choiceOneImg”:“./ images/snatch_images/escape_snatch.png", 错误说找不到模块后面的路径选项。
    • 嗯..由于某种原因它仍然无法正常工作。即使从“images/snatch_images/escape_snatch.png”开始,然后上升 1 级,2 级,然后 3 级(只是为了更加疯狂)。我也遇到了同样的问题……我不确定我的文件结构是否离题了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多