[React-Select触发器onChange值更改时

问题描述 投票:0回答:2

我正在使用React-Select,并且在我的页面上有两个下拉菜单。当选择第一个下拉菜单时,它成功更改了第二个下拉菜单的值,但是我试图在第二个下拉菜单上获取onChange,以便在发生这种情况时也进行更改。有没有办法做到这一点?我做了一个简单的示例代码并尝试完成]

import React, {useState} from "react";
import Select from 'react-select';
import "./styles.css";

export default function App() {
  const [genre, setGenre] = useState()

  const artistslist = [
    {value: 'ACDC', label: 'AC/DC'},
    {value: 'LZ', label: 'Led Zeppelin'},
    {value: 'Garth', label: 'Garth Brooks'},
    {value: 'Alan', label: 'Alan Jackson'}
  ]

  const genrelist = [
    {value: 'rock', label: 'Rock'},
    {value: 'country', label: 'Country'}
  ]

  const handleArtistChange = (event) => {
    console.log(event)
    if (event.value === 'LZ' || event.value === "ACDC") {
      setGenre({value: 'rock', label: 'Rock'})
    } else {
      setGenre({value: 'country', label: 'Country'})
    }
    console.log(genre)
  }

  const handleGenreChange = (event) => {
    console.log("Genre Changed")
  }


  return (
    <div className="App">
      <Select options={artistslist} onChange={handleArtistChange} />
      <Select options={genrelist} value={genre} onChange={handleGenreChange} />
    </div>
  );
}

CodeSandbox Example

reactjs react-select
2个回答
0
投票

This behaviour is not supported by React-Select。但是,只要发生任何更改,您都可以手动调用该函数:

const handleArtistChange = (event) => {
  console.log(event)
  if (event.value === 'LZ' || event.value === "ACDC") {
    setGenre({ value: 'rock', label: 'Rock' })
  } else {
    setGenre({ value: 'country', label: 'Country' })
  }
  console.log(genre)
}

const handleGenreChange = (event) => {
  console.log("Genre Changed")
}

const handleChange = (selector, event) => {
  if (selector === "artist") {
    handleArtistChange(event);
  } else if (selector === "genre") {
    handleGenreChange(event);
  } else {
    // Other logic
  }
  // Here you trigger whatever you want
}

return (
  <div className="App">
    <Select options={artistslist} onChange={event => handleChange("artist", event)} />
    <Select options={genrelist} value={genre} onChange={event => handleChange("genre", event)} />
  </div>
)

0
投票

您只应使用第一个事件的react-select传递的值调用handleGenreChange。您无需从触发另一个事件开始,只需从第一个事件创建一个事件链。

© www.soinside.com 2019 - 2024. All rights reserved.