使用值null反映select [英] React select with value null

查看:96
本文介绍了使用值null反映select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下代码作为我的React组件的一部分:

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

<select
  className="input form-control"
  onChange={this.onUserChanged}
  value={task.user_id}>
  <option value=''></option>
  {this.renderUserOptions()}
</select>

当第一次渲染组件时task.user_id为null时,选择正确显示为值为''的空选项。

When the task.user_id is null on the first rendering of the component, the select is properly displayed with the empty option with value ''.

但是,如果我从具有值的值更改值在默认选项中,服务器端正确更新,任务对象为 task.user_id 返回 null 但是选择不会更改为默认值。

However, if I change the value from something that has a value back to the default option, the server side updates correctly, the task object returns the null for task.user_id but the select doesn't change to the default value.

我应该怎样做才能处理这种情况?

What should I do to handle this scenario?

推荐答案

设置select组件的值时,必须将 null 转换为 '';当您从组件中接收值时,您必须将''转换为 null 。一个简单的例子:

When setting the value for your select component, you will have to convert null to ''; and when receiving the value from your component, you will have to convert '' to null. A simple example:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = { selected: null };
    }

    render() {
        return <div>
            <select
                className="input form-control"
                onChange={e => this.setState({ selected: e.target.value || null })}
                value={this.state.selected || ''}>
                <option value=''></option>
                <option value='1'>cook dinner</option>
                <option value='2'>do dishes</option>
                <option value='3'>walk dog</option>
            </select>
            <input type='button' onClick={() => this.setState({ selected: null })} value='Reset' />
        </div>
    }
}

这假设您的ID总是真实的: e.target.value || null 会将选定的空字符串转换为 null ;和 this.state.selected || ''会将您的 null 状态转换为空字符串。如果您的ID可能是假的(例如数字 0 ),则需要更强大的转换。

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.

请参阅此处的小提琴

这篇关于使用值null反映select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆