Angular 1.X 使用 React 等效的 ng-options

Angular 1.X ng-options equivalent using React

Angular 1.X ng-options select 下拉列表中的选项,每个项目都是 对象。在普通 HTML 中,选项的值只能是 字符串 。当您 select 在 Angular 中选择一个选项时,您可以看到实际的 selected 对象,而在普通 html 中,您只能获得该字符串值。

How do you do the equivalent of that in React (+Redux)?

我想出了一个解决方案,它不使用 JSON.stringify / 解析 select React 元素的值,也不使用选择对象数组的索引作为值。

该示例是一个简单的 select 下拉列表,显示一个人的性别 - 男性或女性。这些选择中的每一个都是具有 id、text 和 value 属性的实际对象。这是代码:

MySelect 组件

import React, { Component } from 'react';

class MySelect extends Component {
  onGenderChange = (event) => {
    // Add the second argument -- the data -- and pass it along
    // to parent component's onChange function
    const data = { options: this.props.options };
    this.props.onGenderChange(event, data);
  }

  render() {
    const { options, selectedOption } = this.props;

    // Goes through the array of option objects and create an <option> element for each
    const selectOptions = options.map(
      option => <option key={option.id} value={option.value}>{option.text}</option>
    );

    // Note that if the selectedOption is not given (i.e. is null),
    // we assign a default value being the first option provided
    return (
      <select
        value={(selectedOption && selectedOption.value) || options[0].value}
        onChange={this.onGenderChange}
      >
        {selectOptions}
      </select>
    );
  }
}

使用 MySelect 的 App 组件

import _ from 'lodash';
import React, { Component } from 'react';

class App extends Component {
  state = {
    selected: null
  }

  onGenderChange = (event, data) => {
    // The value of the selected option
    console.log(event.target.value);
    // The object for the selected option
    const selectedOption = _.find(data.options, { value: parseInt(event.target.value, 10) });
    console.log(selectedOption);

    this.setState({
      selected: selectedOption
    });
  }

  render() {
    const options = [
      {
        id: 1,
        text: 'male',
        value: 123456
      },
      {
        id: 2,
        text: 'female',
        value: 654321
      }
    ];

    return (
      <div>
        <label>Select a Gender:</label>
        <MySelect
          options={options}
          selectedOption={this.state.selected}
          onGenderChange={this.onGenderChange}
        />
      </div>
    );
  }
}

Lodash用于在App组件的onGenderChange函数内部的choice对象数组中查找choice对象。请注意,传递给 MySelect 组件的 onChange 需要两个参数——添加了一个额外的数据参数,以便能够访问选择对象 ("options")。这样,您只需使用 selected 选项的选择对象设置状态(或者如果使用 Redux 则调用动作创建者)。

我 运行 在迁移 angular 1 个应用程序时遇到了同样的情况。我觉得这是一个我找不到的非常需要的功能,所以在这里我将我的 NgOption 实现留在使用 bootstrap 的反应中(你可以将其更改为你正在使用的任何东西)对于任何缺少 goo 的人旧 angular 1:

import React from 'react';
import { Form, InputGroup } from 'react-bootstrap';

interface props<T, U>{
  options: Array<T>,
  selected?: U,
  onSelect: (value: T) => any,
  as: (value: T) => string,
  trackBy: (value: T) => U,
  disabled?: boolean
}

type state = {}

export default class NgOptions extends React.Component<props<any, any>, state> {
  componentDidMount() {
    if (this.props.selected) {
      this.props.onSelect(this.props.options.find((o) => this.props.trackBy(o)===this.props.selected))
    }
  }
  
  public render() {
    return ( <InputGroup>
      <Form.Control as="select"
                    disabled={this.props.disabled}
                    onChange={(e) => this.props.onSelect(this.props.options.find((o) => this.props.trackBy(o)===e.target.value))}>
        {this.props.options.map( option =>
          <option key={this.props.trackBy(option)}
                  selected={this.props.selected===this.props.trackBy(option)}
                  value={this.props.trackBy(option)}>{this.props.as(option)}</option>
        )}
      </Form.Control>
    </InputGroup>
    )
  }
}