简体   繁体   English

React JS - 如何将 json 数据绑定到下拉列表

[英]React JS - How do I bind json data to a dropdown list

I have a react JS file and I'm attempting to bind data to a dropdown list.我有一个反应 JS 文件,我正在尝试将数据绑定到下拉列表。 The data is stored in the following testing API/json file: https://api.myjson.com/bins/okuxu ...I want to start by binding the client name to it's respective dropdown list.数据存储在以下测试 API/json 文件中: https ://api.myjson.com/bins/okuxu ...我想首先将客户端名称绑定到其各自的下拉列表。

Sample json data:示例 json 数据:

[
    {
        "abc_buildingid": "11111112-64c2-5bd8-8b72-e92568694c76",
        "abc_energyprogramid": "5d84ef73-9b9a-475f-84e2-f307ad897df7",
        "siteName": "Construction One",
        "sampleCalibration": false,
        "clientName": "Client-1",
        "segmentName": "John Doe ES New Silver 4-7-2017-04-30-2018~25313~John Doe ES JDU Area Calibration~47851~Mod",
        "cfmRateFactor": 50
    }
]

...this is my code: ...这是我的代码:

import React, { Component } from 'react';

class Ast extends Component {

   constructor(){
       super();
       this.state = {
           data: [],
       };
   } //end constructor

   bindDropDowns() {
       var clientName = document.getElementById('clientName').value

       for(var i=0; i < this.state.data.length; i++) {
        var clientName = this.state.data[i].clientName;
       }
   }

   componentWillMount() {
    fetch('https://api.myjson.com/bins/okuxu', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json',
        },
        /*body: JSON.stringify({
            username: '{userName}',
            password: '{password}'
        })*/
    }) /*end fetch */
    .then(results => results.json()) 
    .then(data => this.setState({ data: data })   
)

} //end life cycle

    render() {
        console.log(this.state.data);
        return (
            <div>


                <form>
                    <div>

                        <h2>Memeber Selection:</h2>

                        <div>

                            <div>
                                <select className="custom-select" id="clientName" onSelect="bindDropDowns()">
                                <option selected>Client</option>
                                </select>     
                            </div><br />

                            <div>
                                <select className="custom-select" id="siteName">
                                <option selected>Site Building Name</option>
                                </select>
                            </div><br />
                            <div>
                                <select className="custom-select" id="segmentName">
                                <option selected>Segments</option>
                                </select>
                            </div><br />
                           <div>
                                <label for="example-text-input">Modify CFM Rate Factor:</label>
                                <input class="form-control" type="textbox"  id="cfmRateFactor" value="10" />
                            </div><br />
                                <div>
                                    <button type="submit" className="btn btn-primary">Submit</button>
                                </div>
                            </div>
                    </div>
                    </form>
            </div>


        );
      }
}

export default Ast

I confirmed via the console that "this.state.data" contains all the information from the json file, so now I'm attempting to bind the client names to a dropdown list.我通过控制台确认“this.state.data”包含来自 json 文件的所有信息,所以现在我正在尝试将客户端名称绑定到下拉列表。 Could I please get some guidance as to what I'm doing wrong?我能得到一些关于我做错了什么的指导吗?

In React, you use a declarative approach instead of DOM manipulation:在 React 中,您使用声明性方法而不是 DOM 操作:

<div>
  {['clientName', 'siteName', 'segmentName'].map(key => (
    <select key={key}>
      {this.state.data.map(({ [key]: value }) => <option key={value}>{value}</option>)}
    </select>
  ))}
</div>

This generates the 3 dropdowns with the options populated.这会生成 3 个下拉菜单,其中填充了选项。

In this.state define the json -this.state定义 json -

CityNames : {
                CityName : 
                    [
                        {CityKey : 1,CityDescription: 'abc'},
                        {CityKey : 2,CityDescription: 'xyz'}
                    ]

        }

Here is the code for Drop Down List这是下拉列表的代码

<select className="form-control">
          <option>---select---</option>
            {
            this.state.CityNames &&
            this.state.CityNames.CityName.map((h, i) => 
            (<option key={i} value={h.CityName}>{h.CityDescription}</option>))
            }
</select>

To populate data into the dropdown list将数据填充到下拉列表中

import your .json file导入您的 .json 文件

<select>
    <option> Select User</option>
      {
       data.map((result)=>(<option title={result.Id}>{result.title}</option>))
      }
</select>

Though your question is not clear, I assume you want to populate the api data into the respective dropdown虽然您的问题不清楚,但我假设您想将 api 数据填充到相应的下拉列表中

To populate data into the respective dropdown list将数据填充到相应的下拉列表中

    <div>
   <select className="custom-select" id="clientName" onSelect="bindDropDowns()">
      this.state.data.map((obj) => 
      <option key={obj.clientName}>{obj.clientName}</option>
      );
   </select>
</div>
<br />
<div>
   <select className="custom-select" id="siteName">
                this.state.data.map((obj) => 
      <option key={obj.siteName}>{obj.siteName}</option>
      );
   </select>
</div>
<br />
<div>
   <select className="custom-select" id="segmentName">
                         this.state.data.map((obj) => 
      <option key={obj.segmentName}>{obj.segmentName}</option>
      );
   </select>
</div>
<br />

If you want to hold your data in a seperate json file;如果您想将数据保存在单独的 json 文件中;

You can declare the data like this.您可以像这样声明数据。

export const Cities = {
    cities : [
        { Key: 1, Value: 'London' },
        { Key: 2, Value: 'New York' },
        { Key: 3, Value: 'Colombo' }    
    ]
}

export default Cities;

And we'll assume that it's in a file called cities.jsx我们假设它在一个名为ities.jsx 的文件中

You import this file in the component where your dropdown list is in like this.您将此文件导入下拉列表所在的组件中,如下所示。

import {Cities} from "../../assets/data/cities.jsx";

(Give the right file path). (给出正确的文件路径)。

Then you can use it on your form control.然后你可以在你的表单控件上使用它。

<FormControl as="select" onChange={(e) => this.handleCities(e)}>
    {Cities.cities && Cities.cities.map((e, key) => {
    return <option key={key} value={e.Key}>{e.Value}</option>;
 })}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM