2017-02-22 46 views
1

角1.X具有ng-options用于在选择下拉菜单中选择,每一个项目作为一个对象。在纯HTML,一个选项的值只能是。当您在Angular中选择一个选项时,您可以在纯html中看到实际选定的对象,只能获取该字符串值。角1.X纳克选项使用阵营

你如何做React(+ Redux)中的等价物?

+0

退房'反应,select'。您还可以创建一个'select'数组作为'option'元素的子元素。 –

+0

@Andy_D感谢您的建议。我实际使用语义UI阵营(http://react.semantic-ui.com/modules/dropdown)和问题是每个选项的值只能是一个字符串。我发现一种解决方法是将对象串化为值。我查看了react-select的源代码,他们这样做。事情是我必须为每个onchange函数做JSON解析。我想知道是否有更好的方法。另一个想法是使用数组索引作为值并访问所有选项,然后使用索引缩小范围。 – nbkhope

回答

0

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

的例子是一个人的性别简单的选择下拉列表 - 无论是男性还是女性。每个选项都是具有id,text和value属性的实际对象。下面是代码:

MySelect部件使用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> 
    ); 
    } 
} 

应用组件

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函数。注意的onChange传递给MySelect组件需要两个参数 - 一个额外的数据参数,以便能够访问选择的对象(“选择”)补充道。就这样,你可以设置状态(或者,如果使用Redux的调用行动的创建者)与所选择的选项的选择对象。