(REACT)如何从Array创建动态选择选项列表

时间:2016-11-28 12:55:40

标签: javascript reactjs

所以,我希望创建一个最终结果是,在.js文件中动态构建的选择选项列表,从数组列表生成,如“'选项”之间所描述的那样。以下代码的一部分。我该怎么做?:



const kvArray = [
  {children: 'Country List', value: 0}, 
  {children: 'France', value: 10}, 
  {children: 'England', value: 20}, 
  {children: 'Peru', value: 30}
].map ((keySelect, index) => ({
  id: index,
  name: keySelect,
}));

class FieldsPage extends React.Component {

  onFormSubmit = () => {
    const { dynamicFields, fields } = this.props;

    const values = {
      ...fields.$values(),
      concepts: {
        ...dynamicFields,
      },
    };
  }

  render() {
    const { fields } = this.props;
    const { disabled, error, submittedValues, selectValue } = this.state;
    
    return (
      <View>
        <Form onSubmit={this.onFormSubmit}>
          <Block>
            <Select
              {...fields.donation}
              disabled={disabled}
              label="Donation"
              options={[
                // What I want to happen here: build selection options by iterating through item, i.e.
                {kvArray.map(item =>
                    { children: item.name.children, value: item.name.value},
                )}

              ]}
            />
          </Block>
          <Button disabled={disabled} type="submit">
            <FormattedMessage {...buttonsMessages.submit} />
          </Button>

        </Form>
      </View>
    );
  }

}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以在数组中设置选项并迭代它 例如

setFruits(){
      const fruits = [<option key={1} value="grapefruit">Grapefruit</option>,<option key={2} value="lime">Lime</option>,<option key={3} value="coconut">Coconut</option>,<option key={4} value="mango">Mango</option>];
      this.setState({fruits:fruits});

    }
render() {

        return (
            <div>
                <select>
                  {this.state.fruits}
                </select>                
            </div>
        );
    };

答案 1 :(得分:0)

因此,经过进一步调查,我的问题的解决方案如下:

&#13;
&#13;
// Proof of concept. Country list will be read from firebase
const countryArray = [
  { label: 'Select Country', value: 0 },
  { label: 'France', value: 2 },
  { label: 'England', value: 4 },
  { label: 'Swizterland', value: 8 },
  { label: 'Germany', value: 16 },
  { label: 'Lithuania', value: 32 },
  { label: 'Romania', value: 64 }
].map ((countryName, index) => ({
  id: index,
  name: countryName,
}));

// Dynamically create select list
let options = [];
countryArray.map(item =>
  options.push({ label: item.name.label, value: item.name.value }),
);

<Select
  {...fields.donation}
  disabled={disabled}
  label="Countries"
  onChange={this.selectCity}
  options={options}
/>
&#13;
&#13;
&#13;