Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

reactjs - React, Show images using style-component

I have a question about allocating images dynamically.

I tried to show each images by each cases(depending each data's type and totalCount).

But this code is not working.

export default function Title() {
    let image =
  "../../../assets/images/situations/situation_" + totalCount + ".png";
    return (
        <>
        {types[totalCount - 1] === "situation" ? 
        <SituationTitleStyled img={image}>
        ...
        </SituationTitleStyled>
       }
       </>
    )
}

const SituationTitleStyled = styled.div`
    ...
    background: url(${(props) => props.image});
`;

Otherwise, if the variable "image" is absolute path like "https://mdn.mozillademos.org/files/7693/catfront.png", then it works.

I don't know how i can this work and what is the diffence between using absolute path and relative path. :0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A path should be generated by webpack:

You can import a file right in a JavaScript module. This tells webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.

So in your code you can just call require:

let image = require("../../../assets/images/..." + totalCount + ".png");

See almost duplicated question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...