我想用 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>
);
图像正确显示。
如果我编写第一个代码,即为选择框中的每个项目获取不同图片的代码,我会遇到错误:
在 react 中不使用 img 的 require 函数的任何解决方案?
编辑:
我也试过:
const IconOption = (props) =>
(
<Option {... props}>
<div>
<img src={props.data.image} />
{props.data.label}
</div>
</Option>
);
我没有找到图片:
最佳答案
你只需要删除 require
因为你的图像不是编译的 React 应用程序的一部分:
const IconOption = (props) => (
<Option {... props}>
<div>
<img src={props.data.image} />
</div>
</Option>
);
关于reactjs - 使用图像作为 react 选择的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57127583/