reactjs - 使用图像作为 react 选择的图标

标签 reactjs image require react-select

我想用 react-select 添加一个图像作为图标。我做得很好,但我有一个问题,在 react 中,图像是这样写的:

<img src={require(...)} />

所以我像这样使用 react-select :

const IconOption = (props) => (

  <Option {... props}>
    <div>
      <img src={require(props.data.image)} />
    </div>
  </Option>
);

然后调用选择框:

render() {
    return (
      <Select
        classNamePrefix="react-select"
        placeholder={"Search..."}
        onChange={this.handleChange}
        components={{ DropdownIndicator: () => null, Option: IconOption }}
        options={this.state.options}
        openMenuOnClick={false}
        styles={customStyle}
      />
    );
  }

我试着写:

const IconOption = (props) => (

  <Option {... props}>
    <div>
      {props.data.image}
    </div>
  </Option>
);

这给了我:

./css/img/PROFILEPICTURE.jpg

正是我想要得到的,路径是正确的。如果我准确地写:

const IconOption = (props) => (

  <Option {... props}>
    <div>
      <img src="./css/img/PROFILEPICTURE.jpg" />
    </div>
  </Option>
);

图像正确显示。

如果我编写第一个代码,即为选择框中的每个项目获取不同图片的代码,我会遇到错误:

enter image description here

在 react 中不使用 img 的 require 函数的任何解决方案?

编辑:

我也试过:

const IconOption = (props) => 
  (
    <Option {... props}>
      <div>
        <img src={props.data.image} />
        {props.data.label}
      </div>
    </Option>
  );

我没有找到图片:

enter image description here

最佳答案

你只需要删除 require 因为你的图像不是编译的 React 应用程序的一部分:

const IconOption = (props) => (
  <Option {... props}>
    <div>
      <img src={props.data.image} />
    </div>
  </Option>
);

关于reactjs - 使用图像作为 react 选择的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57127583/

相关文章:

reactjs - MobX,Store 不可用,请确保它是由某些提供商提供的

reactjs - 如何使用 react-pdf 库创建表格以生成 pdf 报告?

ruby - 在 Ruby 中要求目录中所有文件的最干净/单行方法?

PHP require_once 绝对路径与相对路径(不工作)

CSS 增加 +100% 图像不透明度,可能吗?

mysql - 如果我可以在 node-mysql 的回调中执行 "require",模块函数是添加到回调范围还是全局范围?

reactjs - useForm 在既不是 React 函数组件的函数中被调用...错误

reactjs - 如何解决 redux 连接函数抛出的 "bubble up"错误?

wpf - WPF应用程序中的图像显示比在外部查看器中查看的图像小

c# - 图像属性的值 (C#)