最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJs Select add default value - Stack Overflow

programmeradmin2浏览0评论

I want to store select default value if user not touch it in ReactJs. How is that possible?

<select onChange={this.valSelected.bind(this)}>
    {currencies.map(function(name, index){
        return <option value={name}>{name}</option>;
    })}
</select>

and

valSelected(event){
    this.setState({
        valSelected: event.target.value
    });
}

I want to store select default value if user not touch it in ReactJs. How is that possible?

<select onChange={this.valSelected.bind(this)}>
    {currencies.map(function(name, index){
        return <option value={name}>{name}</option>;
    })}
</select>

and

valSelected(event){
    this.setState({
        valSelected: event.target.value
    });
}
Share Improve this question asked Aug 14, 2016 at 15:12 IntoTheDeepIntoTheDeep 4,11815 gold badges45 silver badges86 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

You can just add a value property to the select element, set by your state.

<select value={this.state.valSelected} onChange={this.valSelected.bind(this)}>
    {currencies.map(function(name, index){
        return <option value={name}>{name}</option>;
    })}
</select>

This is described here in the react docs: Doc Link

Then set a default state for the component, either in the constructor or with getInitialState: What is the difference between using constructor vs getInitialState in React / React Native?

Use defaultValue to select the default value.

    const statusOptions = [
        { value: 1, label: 'Publish' },
        { value: 0, label: 'Unpublish' }
    ];
    const [statusValue, setStatusValue] = useState('');
    const handleStatusChange = e => {
        setStatusValue(e.value);
    }

return(
<>
<Select options={statusOptions} defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]} onChange={handleStatusChange} value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)
发布评论

评论列表(0)

  1. 暂无评论