React JSX:在选定的<select>选项上选择“ selected”

<select>菜单的React组件中,我需要selected在反映应用程序状态的选项上设置属性。

在中render(),将optionState其从状态所有者传递到SortMenu组件。选项值props从JSON 传入

render: function() {
  var options = [],
      optionState = this.props.optionState;

  this.props.options.forEach(function(option) {
    var selected = (optionState === option.value) ? ' selected' : '';

    options.push(
      <option value={option.value}{selected}>{option.label}</option>
    );
  });

// pass {options} to the select menu jsx

但是,这会在JSX编译上触发语法错误。

这样做可以摆脱语法错误,但显然不能解决问题:

var selected = (optionState === option.value) ? 'selected' : 'false';

<option value={option.value} selected={selected}>{option.label}</option>

我也尝试过这个:

var selected = (optionState === option.value) ? true : false;

<option value={option.value} {selected ? 'selected' : ''}>{option.label}</option>

有解决此问题的推荐方法吗?

番长樱梅2020/03/09 23:30:16

I got around a similar issue by setting defaultProps:

ComponentName.defaultProps = {
  propName: ''
}

<select value="this.props.propName" ...

So now I avoid errors on compilation if my prop does not exist until mounting.

ProTony2020/03/09 23:30:16

Posting a similar answer for MULTISELECT / optgroups:

render() {
  return(
    <div>
      <select defaultValue="1" onChange={(e) => this.props.changeHandler(e.target.value) }>
        <option disabled="disabled" value="1" hidden="hidden">-- Select --</option>
        <optgroup label="Group 1">
          {options1}
        </optgroup>
        <optgroup label="Group 2">
          {options2}
        </optgroup>
      </select>
    </div>
  )
}
飞云西里神乐2020/03/09 23:30:16

这是一个完整的解决方案,其中结合了最佳答案和其下的评论(这可能会帮助某人努力将其拼凑在一起):

ES6的更新(2019)-使用箭头功能和对象分解

在主要组成部分:

class ReactMain extends React.Component {

  constructor(props) {
    super(props);
    this.state = { fruit: props.item.fruit };
  }

  handleChange = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  }

  saveItem = () => {
    const item = {};
    item.fruit = this.state.fruit;
    // do more with item object as required (e.g. save to database)
  }

  render() {
    return (
      <ReactExample name="fruit" value={this.state.fruit} handleChange={this.handleChange} />
    )
  }

}

包含的组件(现在是无状态功能):

export const ReactExample = ({ name, value, handleChange }) => (
  <select name={name} value={value} onChange={handleChange}>
    <option value="A">Apple</option>
    <option value="B">Banana</option>
    <option value="C">Cranberry</option>
  </select>
)

上一个答案(使用bind):

在主要组成部分:

class ReactMain extends React.Component {

  constructor(props) {
    super(props);
    // bind once here, better than multiple times in render
    this.handleChange = this.handleChange.bind(this);
    this.state = { fruit: props.item.fruit };
  }

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

  saveItem() {
    const item = {};
    item.fruit = this.state.fruit;
    // do more with item object as required (e.g. save to database)
  }

  render() {
    return (
      <ReactExample name="fruit" value={this.state.fruit} handleChange={this.handleChange} />
    )
  }

}

包含的组件(现在是无状态功能):

export const ReactExample = (props) => (
  <select name={props.name} value={props.value} onChange={props.handleChange}>
    <option value="A">Apple</option>
    <option value="B">Banana</option>
    <option value="C">Cranberry</option>
  </select>
)

the main component maintains the selected value for fruit (in state), the included component displays the select element and updates are passed back to the main component to update its state (which then loops back to the included component to change the selected value).

Note the use of a name prop which allows you to declare a single handleChange method for other fields on the same form regardless of their type.

十三西里古一2020/03/09 23:30:16

只需将select标签添加为第一个选项:

<option disabled hidden value=''></option>

这将成为默认设置,当您选择有效选项时,您的状态将被设置

梅老丝2020/03/09 23:30:16

您可以尝试在尝试设置的“ selected”属性时React警告您<option>

在上使用defaultValuevalue道具,<select>而不是在selected进行设置<option>

因此,您可以options.valuedefaultValue选择的

A小宇宙2020/03/09 23:30:16

React为此自动理解布尔值,因此您可以简单地编写(注意:不推荐)

<option value={option.value} selected={optionsState == option.value}>{option.label}</option>

并将适当地输出“已选择”。

但是,React使您更加轻松。除了定义selected每个选项,您可以(并且应该)简单地value={optionsState}在select标记本身上编写

<select value={optionsState}>
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

有关更多信息,请参见React select标签doc