【发布时间】:2019-08-04 16:21:46
【问题描述】:
如何使用material-ui 在下拉列表中显示默认值?我尝试添加displayEmpty="true",但没有任何改变。
我希望默认选择第一个选项A,以便用户可以在 UI 中看到它。目前,用户应该单击下拉菜单以从列表中选择一个项目。默认不选中任何项目(默认选中的项目为空白)。
const options = [
{label:"A",value:483.93},
{label:"B",value:8033.86},
{label:"C",value:1246.3}
]
<Grid item xs={true}>
<FormControl
className={this.props.styles.formControl}
margin="normal">
<InputLabel shrink htmlFor="distanceTarget-label-placeholder">
Target:
</InputLabel>
<Select
onChange={(event) => this.props.handleChange("distanceTarget", event)}
value={this.props.state.distanceTarget}
input={<Input name="distanceTarget" id="distanceTarget-label-placeholder" />}
displayEmpty="true"
name="distanceTarget"
>
{options && options.length && options.map((option, i) => {
return <MenuItem value={option.value} key={i}>{option.label}</MenuItem>
})}
</Select>
</FormControl>
</Grid>
更新:
这是我在 cmets 中建议的尝试,但是我仍然遇到同样的问题:
{options && options && options((option, i) => {
if (i===0) {
return <MenuItem value={option.value} key={i} selected={true}>{option.label}</MenuItem>
}
else {
return <MenuItem value={option.value} key={i}>{option.label}</MenuItem>
}
})}
【问题讨论】:
-
为要默认选中的元素设置
selected = true -
@CodeManiac:我如何在
map中做到这一点?类似if i==0 then...? -
是的,使用
if...else并根据您的要求返回带有和不带有selected属性的MenuItem,即 i == 0 ?<MenuItem selected={true}...:<MenuItem value={option.value} key={....... -
@CodeManiac:我试过这种方法,但没有出现默认值。请参阅我的代码更新。
标签: javascript reactjs material-ui