我想将图像放在对象或数组中,并在需要时使用它们。我应该怎么办?

I want to put the images in an object or array and use them when I need them. What should I do?

我希望我可以将所有图像放入 'Image.jsx' 文件,并在 React

中轻松地将它们从另一个文件中取出

例如

export const Header = ({ title, children }) => {
  return (
    <>
      <Title>{title}</Title>
      <Items>{children}</Items>
    </>
  );
};
Header.propTypes = {
  title: PropTypes.node,
  children: PropTypes.object,
}; 
// I made a separate component. And the codes in the component will be used in other files.

import { Header } from "../BaseLabel";
const FriendstHeader = () => {
  return (
    <>
      <FriendContainer>
        <Header title="친구" style={{ color: "#191919" }}/>
      </FriendContainer>
    </>
  );
};
export default FriendstHeader;

我要管理图片。就像这个例子。这是Image.jsx

import React from 'react';
import PropTypes from 'prop-types';
import Search from "images/search.png";

const imageSrc = [ Search ];
export const Image = (props: imageSrc) => {
  return (
   <>
     <img alt="">{imageSrc.Search}</img>
   </>
  );
};
Image.propTypes = {
  imageSrc: PropTypes.node,
};

这是将显示图像的主屏幕。

import React from 'react';
import Search from "images/search.png";

const Header = () => {
  return(
    <>
     <Items>
       <img src={Search} width="18px" height="18px" alt="" />
     </Items>
    </>
  )
}
export default Header;

其实图片不是一张,只是为了不显得复杂,缩成一张上面了

实际上在代码中捆绑图像是个坏主意。 您应该将图像或静态文件移动到 publicpublic/images(这样更有意义)。

那你的Image.jsx可以这样

import React from 'react';

const Image = ({src, alt="", ...rest }) => {
    return <img src={src} alt={alt} {...rest}/>
}

export default Image;

之后,您可以像这样使用 Image 组件:

import React from 'react';

const Test = () => {
   return 
<div>
   <p>Hello world</p>       
   <Image src="/images/Search.png" width="20" height="20" style={{ marginBottom: 10 }} onClick={() => {}} alt="This is alt for search image"/>
</div>
}

export default Test;