目标
我需要开发一个单选下拉菜单,允许用户从不同的图像而不是单词中进行选择。
背景
我已经下载了react下拉列表并导入到文件中。如果我使用文字,则该下拉列表有效,但是我没有成功使它显示图像。
我尝试过的事情
首先,在this.state中,我尝试向图像文件添加相对路径。这只是渲染了该路径(duh)。接下来,我尝试添加带有src的img标签,指向我要显示的图像的位置。结果是一张图像,似乎表明该图像应该存在。
这里是代码
import React from 'react';
import './EventContainer.css';
import { Dropdown } from 'reactjs-dropdown-component';
import { dining } from './EventContainerIcons.js';
class EventContainer extends React.Component {
constructor(props){
super(props);
this.state = {
...props.event,
activityIcon: [
{
id: 0,
title: <img src={dining} width="64" height="64" alt="dining icon" />,
selected: false,
key: 'activityIcon'
},
{
id: 1,
title: 'Orange',
selected: false,
key: 'activityIcon'
},
{
id: 2,
title: 'Strawberry',
selected: false,
key: 'activityIcon'
}
],
};
}
handleTypeChange = (e) => {
this.setState({
type: e.target.value
})
}
handleTimeChange = (e) => {
this.setState({
time: e.target.value
})
}
handleSummaryChange = (e) => {
this.setState({
summary: e.target.value
})
}
handleNotesChange = (e) => {
this.setState({
notes: e.target.value
})
}
resetThenSet = (id, key) => {
let temp = JSON.parse(JSON.stringify(this.state[key]));
temp.forEach(item => item.selected = false);
temp[id].selected = true;
this.setState({
[key]: temp
});
}
render(){
return (
<div className="eventContainer-flex">
<Dropdown
title="Event Type"
list={this.state.activityIcon}
resetThenSet={this.resetThenSet}
/>
<div>
<input
type="time"
value={this.state.time}
onChange={this.handleTimeChange}/>
</div>
<div>
<textarea
className="textarea-font"
placeholder="Write summary here"
value={this.state.summary}
onChange={this.handleSummaryChange}
cols={60}
rows={3} />
</div>
<div>
<textarea
className="textarea-font"
placeholder="Write notes here"
value={this.state.notes}
onChange={this.handleNotesChange}
cols={30}
rows={3} />
</div>
</div>
)
}
}
export default EventContainer;
只需将图像名称添加到导入中。像
import image from './EventContainerIcons/dining.png';
此后,
title: <img src={image} alt="empty" />
仅供参考:在使用图像时,向img标签添加alt属性。