首页 > 解决方案 > Insert image within imported React component (SOLVED!)

问题描述

(SOLVED, see answer below)

I want to add an image inside each accordion section and I've tried to use <img src={Image}/>. If that piece of code is placed as in the screenshot it works, but it's located outside of the < Accordion >.

If I move the code inside < Accordion > it stops working and I can't figure out exactly how to fix this. A thought was to somehow use image like {props.title} and {props.content} but could not get it to work.

Any suggestions?

code in component FirstAccordion.js

Accordion.js // component with the accordion logic

return (
        <div className="accordion-section">
            <button className={`accordion-button ${setActive}`} onClick={toggleAccordion}>
                <p className="accordion-title">{props.title}</p>
                    <Chevron
                        className={`${setRotate}`}
                        width={10}
                        fill={"#777"}
                    />
            </button>
        
            <div 
                ref={content}
                className="accordion-content"
                style={{ maxHeight: `${setHeight}` }}>
            
            <div
                className="accordion-text"
                // the prop dangerouslySetInnerHTML makes it possible to use HTML within a string
                dangerouslySetInnerHTML={{ __html: props.content }}  
                />

            </div>
        </div>

FirstAccordion.js // component in which I import accordion logic

export function FirstAccordion() {
    
    return (
        <>
        <Sidebar />
        <Navbar />
        <h1 className="h1-accordion">Pregnancy Week By Week</h1>
        <section className="accordion-background">
        <div className="accordion-wrapper">
        <div className="accordion-container-cne">
            <Accordion
            title="Week 1"
            content="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."/>

标签: reactjsimagedangerouslysetinnerhtml

解决方案


Change this:

<div
  className="accordion-text"
  dangerouslySetInnerHTML={{ __html: props.content }}
/>

Too:

<div className="accordion-text">{props.children}</div>

You should then be able to use the accordion like this:

<Accordion title="Week 1">
  <p>Hello World</p>
  <img src={...} />
</Accordion>

You probably have to adjust to your needs.


推荐阅读