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

在render()中,optionState从状态所有者传递给SortMenu组件。选项值作为道具从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>

有没有解决这个问题的推荐方法?


当前回答

下面是一个完整的解决方案,包含了最佳答案和下面的评论(这可能会帮助那些挣扎着把它们拼凑在一起的人):

UPDATE FOR 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>
)

之前的答案(使用绑定):

在主要组成部分:

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>
)

主组件维护fruit的选中值(处于状态),被包含的组件显示select元素并将更新传递回主组件以更新其状态(然后循环回被包含的组件以更改所选值)。

请注意,使用了名称道具,它允许您为同一表单上的其他字段声明一个handleChange方法,而不管它们的类型是什么。

其他回答

***Html:***
<div id="divContainer"></div>

var colors = [{ Name: 'Red' }, { Name: 'Green' }, { Name: 'Blue' }];
var selectedColor = 'Green';

ReactDOM.render(<Container></Container>, document.getElementById("divContainer"));

var Container = React.createClass({
    render: function () {
        return (
        <div>            
            <DropDown data={colors} Selected={selectedColor}></DropDown>
        </div>);
    }
});

***Option 1:***
var DropDown = React.createClass(
{
    render: function () {
        var items = this.props.data;
        return (
        <select value={this.props.Selected}>
            {
                items.map(function (item) {
                    return <option value={item.Name }>{item.Name}</option>;
                })
            }
        </select>);
    }
});

***Option 2:***
var DropDown = React.createClass(
{
    render: function () {
        var items = this.props.data;
        return (
        <select>
            {
                items.map(function (item) {
                    return <option value={item.Name} selected={selectedItem == item.Name}>{item.Name}</option>;
                })
            }
        </select>);
    }
});

***Option 3:***
var DropDown = React.createClass(
    {
        render: function () {
            var items = this.props.data;
            return (
            <select>
                {
                    items.map(function (item) {

                                            if (selectedItem == item.Name)
                    return <option value={item.Name } selected>{item.Name}</option>;
                else
                    return <option value={item.Name }>{item.Name}</option>;
                    })
                }
            </select>);
        }
    });

如果你使用无状态,那么

const IndexPage =({states, selectedState}) => {
return(
    <select id="states" defaultValue={selectedState} name="state">
{states.map(state=> (
                      <option value={state.id} key={state.id}>{state.name}</option>
                      ))
                      }
                    </select>
)
}

我有一个问题,<选择>标签没有更新到正确的<选项>时,状态改变。我的问题似乎是,如果你连续渲染两次,第一次没有预先选择<选项>,但第二次有一个,那么<select>标签不会在第二次渲染时更新,而是首先保持默认值。

我找到了一个使用裁判的解决方案。您需要获得对<select>标记节点(可能嵌套在某些组件中)的引用,然后在componentDidUpdate钩子中手动更新该节点上的value属性。

componentDidUpdate(){
  let selectNode = React.findDOMNode(this.refs.selectingComponent.refs.selectTag);
  selectNode.value = this.state.someValue;
}

我有一个简单的解决方案是遵循HTML基本。

<input
  type="select"
  defaultValue=""
  >
  <option value="" disabled className="text-hide">Please select</option>
  <option>value1</option>
  <option>value1</option>
</input>

.text-hide是一个bootstrap的类,如果你不使用bootstrap,这里是:

.text-hide {
  font: 0/0 a;
  color: transparent;
  text-shadow: none;
  background-color: transparent;
  border: 0;
}

当你试图设置<option>的"selected"属性时,你可以做React警告你的事情:

在<select>上使用defaultValue或value道具,而不是在<option>上使用设置。

所以,你可以使用选项。在您选择的defaultValue上