React select with value null

后端 未结 2 2122
滥情空心
滥情空心 2021-02-07 00:34

I have the following code as part of my React component:

 this.setState({ selected: e.target.value || null })}
                value={this.state.selected || ''}>
                
                
                
                
            
             this.setState({ selected: null })} value='Reset' />
        
} }

This works assuming that your ids are always truthy: e.target.value || null will convert the selected empty string to null; and this.state.selected || '' will convert your null state to an empty string. If your ids can be falsey (for example the number 0), you will need a more robust conversion.

See Fiddle here.

提交回复
热议问题