当用户单击输入字段时,在响应中动态显示列表

时间:2019-02-14 00:13:53

标签: reactjs input

我试图在用户单击输入框时动态显示列表。为此,我在输入框上使用了onChange事件句柄,并在用户单击输入框时将状态设置为新数据。但这并没有给我想要的结果。谁能帮助我解决这个问题?当用户单击输入框时,仅应显示列表,但就我而言,它已经显示。

SearchBox.js

import React, { Component } from "react";
import SourceData from "../assets/continents.json";

class SearchBox extends Component {
  state = {
    value: ""
  };

  handleChange = e => {
    this.setState({
      sourceData: SourceData
    });
  };

  render() {
    const searhBox = (
      <input type="text" value={this.state.value} onClick={this.handleChange} />
    );
    const selectBox2 = SourceData.map(option => <li>{option.continent}</li>);

    return (
      <React.Fragment>
        <h2>Step 1</h2>
        <h3>Select a continent.</h3>
        {searhBox}
        <ul>{selectBox2}</ul>
      </React.Fragment>
    );
  }
}

export default SearchBox

continents.json

[
  {
    "continent": "Africa",
    "countries": [
      {
        "name": "Nigeria",
        "flag": "ð³ð¬"
      },
      {
        "name": "Ethiopia",
        "flag": "ðªð¹"
      },
      {
        "name": "Egypt",
        "flag": "ðªð¬"
      },
      {
        "name": "DR Congo",
        "flag": "ð¨ð©"
      },
      {
        "name": "South Africa",
        "flag": "ð¿ð¦"
      }
    ]
  },
  {
    "continent": "America",
    "countries": [
      {
        "name": "USA",
        "flag": "ðºð¸"
      },
      {
        "name": "Brazil",
        "flag": "ð§ð·"
      },
      {
        "name": "Mexico",
        "flag": "ð²ð½"
      },
      {
        "name": "Colombia",
        "flag": "ð¨ð´"
      },
      {
        "name": "Argentina",
        "flag": "ð¦ð·"
      }
    ]
  },
  {
    "continent": "Asia",
    "countries": [
      {
        "name": "China",
        "flag": "ð¨ð³"
      },
      {
        "name": "India",
        "flag": "ð®ð³"
      },
      {
        "name": "Indonesia",
        "flag": "ð®ð©"
      },
      {
        "name": "Pakistan",
        "flag": "ðµð°"
      },
      {
        "name": "Bangladesh",
        "flag": "ð§ð©"
      }
    ]
  }

 ]

输出::

enter image description here

1 个答案:

答案 0 :(得分:2)

SearchBox.render中,建立this.state.sourceData中的国家/地区列表

const selectBox2 = this.state.sourceData.map(option => <li>{option.continent}</li>);

return (
  <React.Fragment>
    <h2>Step 1</h2>
    <h3>Select a continent.</h3>
    {searhBox}
    {selectBox2 && <ul>{selectBox2}</ul>}
  </React.Fragment>
);

另外,请记住在sourceData中为SearchBox.state设置一个初始值。

state = {
   value: '',
   sourceData: []
};