簡體   English   中英

如何在第二個自動完成輸入中獲取特定數據,這取決於在 React.js 中的第一個輸入中鍵入的內容?

[英]How to get a certain data in the second autocomplete input that depend on what typed in the first input in React.js?

好的,所以我不知道如何正確表達我的簡單問題,因為它很簡單,我猜。

基本上,我在我的 React 項目中完成了一個自動完成功能。我有兩個輸入“國家”和“城市”。 當我輸入一個國家/地區時,我的自動完成功能非常好,可以給我一些建議,但現在我必須為我的第二個輸入做同樣的事情,所以它會給我一個城市列表,這取決於在“國家”輸入中輸入的國家...

“英國”=>“倫敦、伯明翰、拜頓等”

我怎樣才能做到這一點? 謝謝!

PS我已經有了所有國家和城市的列表,我只是不知道如何使第二個輸入依賴於第一個中的信息。

代碼在這里

Autocomplete.jsx https://github.com/lembas-cracker/Weather-app/blob/master/src/Autocomplete.jsx

Form.jsx https://github.com/lembas-cracker/Weather-app/blob/master/src/Form.jsx

PS我已經有了所有國家和城市的列表,我只是不知道如何使第二個輸入依賴於第一個中的信息。

如果您知道該城市屬於哪個國家/地區(可能通過 city 對象中的鍵),您可以運行一個簡單的filter功能來刪除任何不屬於該國家/地區的城市。

this.state = {
    selectedCountry: 'London',
};

const cities = [
    { name: "Toronto", country: "Canada" },
    { name: "London", country: "United Kingdom" }
];

const filteredCities = cities.filter(city => {
    return city.country !== this.state.selectedCountry;
});

在您的城市輸入字段上,確保創建一個onBlur函數,以便在用戶離開該輸入字段后在您的城市列表上運行過濾器。

做了一個簡單的例子。 你的意思是這樣的嗎? 由於您沒有提供源代碼的任何部分,因此我使用純 HTML select進行演示。

https://jsfiddle.net/arfeo/n5u2wwjg/204186/

class App extends React.Component {
    constructor() {
    super();

    this.state = {
        countryId: 1,
    };
  }

  onCountryChange(countryId) {
    this.setState({ countryId: parseInt(countryId) });
  }

    render() {
    return (
        <div>
        <Input
          key="countriesInput"
          type="countries"
          countryId={this.state.countryId}
          onChange={(countryId) => this.onCountryChange(countryId)}
        />
        <Input
          key="citiesInput"
          type="cities"
          countryId={this.state.countryId}
        />
      </div>
    );
  }
}

class Input extends React.Component {
    constructor() {
    super();

    this.selectRef = null;
  }

    renderOptions() {
    const countries = [
        {
        id: 1,
        name: 'England',
      },
      {
        id: 2,
        name: 'Germany',
      },
      {
        id: 3,
        name: 'France',
      },
    ];

    const cities = [
        {
        countryId: 1,
        cities: [
            {
            id: 1,
            name: 'London',
          },
            {
            id: 2,
            name: 'Liverpool',
          },
          {
            id: 3,
            name: 'Salisbury'
          }
        ],
      },
      {
        countryId: 2,
        cities: [
            {
            id: 4,
            name: 'Berlin',
          },
          {
            id: 5,
            name: 'Frankfurt',
          },
        ],
      },
      {
        countryId: 3,
        cities: [
            {
            id: 6,
            name: 'Paris',
          },
        ],
      },
    ];

    switch (this.props.type) {
        case 'countries': {
        return countries.map((country) => (
          <option
            key={country.id.toString()}
            value={country.id}
          >
            {country.name}
          </option>
        ));
      }
        case 'cities': {
        const citiesMap = cities.filter((city) => city.countryId === this.props.countryId);

        if (citiesMap && citiesMap[0]) {
            const citiesList = citiesMap[0].cities;

          if (citiesList) {
            return citiesList.map((city) => (
              <option
                key={city.id.toString()}
                value={city.id}
              >
                {city.name}
              </option>
            ));
          }
        }

        return null;
      }
      default: return null;
    }
  }

    render() {
    return (
        <select name={this.props.type} ref={(ref) => this.selectRef = ref} onChange={() => this.props.onChange(this.selectRef.value)}>
        {this.renderOptions()}
      </select>
    );
  }
}

ReactDOM.render(<App />, document.querySelector("#app"))

更新

  1. 使您的Form組件有狀態。

  2. Form中為countries添加一個 state 屬性(讓它成為countryId )。

  3. 將此屬性作為道具傳遞給第二個Autocomplete組件。

  4. 當第一個Autocomplete更改時,更改FormcountryId

我做過類似的事情,可能會對你有所幫助。

您可以使用Object.keys(instutiontypes)來擁有一系列國家/地區。 然后在這些值中,您可以擁有一個對象數組。 您可以在這里擁有城市,例如{value: "Manchester", "label: Manchester", phoneExt: "0114"}

const instutiontypes =  {
Kindergarten: [
    { value: "PreK", label: "PreK" },
    { value: "K1", label: "K1" },
    { value: "K2", label: "K2" },
    { value: "K3", label: "K3" },
  ],
  "Primary School": [
    { value: "Grade 1", label: "Grade 1" },
    { value: "Grade 2", label: "Grade 2" },
    { value: "Grade 3", label: "Grade 3" },
    { value: "Grade 4", label: "Grade 4" },
    { value: "Grade 5", label: "Grade 5" },
    { value: "Grade 6", label: "Grade 6" },
  ],
}

為了在我的輸入中有選項,我使用Object.keys(instutiontypes)來獲取['Kindergarten','Primary School']

然后,為了獲得要給我的輔助下拉列表的年齡數組,我編寫了以下代碼:

const types = ['Selection1', 'Selection2']

  const agesList = [];

  for (let i = 0; i < types.length; i++) {
    Object.values(institutionTypes[types[i]]).map(({ label }) =>
      agesList.push(label)
    );
  }

這樣, ages下拉列表取決於傳遞給institutionTypes類型的值。

我正在使用 mui 的<Autocomplete />組件使它們成為搜索下拉列表,並帶有數組的 prop options

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM