如何在反应中默认选择选项

时间:2019-06-19 09:17:53

标签: reactjs

我在选项标签中使用this.state.something使其选择为默认。 但这显示了this.state.editusertype

上的错误
<select name="usertype" className="form-control" value={this.state.editusertype}>
 <option value="">Select</option>
 <option value="Employee" {this.state.editusertype == "Employee" ? "selected" : ""} >Employee</option>
 <option value="Manager" {this.state.editusertype == "Manager" ? "selected" : ""}>Manager</option>
</select>

2 个答案:

答案 0 :(得分:0)

如果要使用默认选项,请为select标签设置默认值。它应该与匹配选项相对应。查看沙盒:https://codesandbox.io/s/young-pine-zmpvr

class App extends React.Component {
  state = {
    editusertype: "Manager"
  };

  handleOnChange = event => {
    this.setState({
      editusertype: event.target.value
    });
  };

  render() {
    return (
      <div>
        <select
          name="usertype"
          className="form-control"
          onChange={this.handleOnChange}
          value={this.state.editusertype}
        >
          <option value="">Select</option>
          <option value="Employee">Employee</option>
          <option value="Manager">Manager</option>
        </select>
      </div>
    );
  }
}

handleOnChange()用于在选择其他项目时更改值。

答案 1 :(得分:0)

我建议您使用react-select

admin: {
  type: Object,
  users: [{
    _id: false
  }]
}
.
.
//rest of the schema