如果值与React Selectbox中的其他值匹配,如何默认获取选定值?

时间:2018-06-02 07:14:53

标签: javascript html reactjs

我正在通过将数据转换为表单来更新数据。在表单中,我从数据库中获取数据。问题是当我在selectbox中获取数据并希望显示默认选择值时,如果它与数据库字段数据匹配。

<select disabled ref = {(input)=> this.menu = input} value={this.state.category} onChange={this.handleCat} className="form-control" name="category" data-toggle="tooltip" data-trigger="hover"className="form-control tooltips" title="Select Course Category">

<option disabled>Select Category</option>
{
this.state.categoryData.map((item, index) =>(
<option key={index} value={item._id}>{item.category}</option>
))
}
</select>

1 个答案:

答案 0 :(得分:2)

您可以在value={defaultValue}标记本身上写下select

&#13;
&#13;
class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: [
        {
          value: "Grapefruit",
          default: false
        },
        {
          value: "Lime",
          default: true
        },
        {
          value: "Coconut",
          default: false
        },
        {
          value: "Mango",
          default: false
        }
      ]
                 };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.getDefaultValue = this.getDefaultValue.bind(this);
  }

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

  handleSubmit(event) {
    alert('Your favorite flavor is: ' + this.state.value);
    event.preventDefault();
  }
  
  getDefaultValue() {
    return this.state.options.filter( ( el ) => {
      return el.default == true;
    } )[0].value;
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite La Croix flavor:
          <select value={this.getDefaultValue()} onChange={this.handleChange}>
            {
              this.state.options.map( (el, index) => {
                return( <Option value={el.value} key={index} /> );
              } )
            }
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

const Option = ( props ) => (
  <option value={props.value}>{props.value}</option>
);

ReactDOM.render(
  <FlavorForm />,
  document.getElementById('root')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;

了解更多here