gpt4 book ai didi

reactjs - React-Select 当值改变时触发 onChange

转载 作者:行者123 更新时间:2023-12-02 02:53:03 25 4
gpt4 key购买 nike

我正在使用 React-Select,并且我的页面上有两个下拉菜单。当选择第一个下拉列表时,它会成功更改第二个下拉列表的值,但我试图在发生这种情况时使第二个下拉列表上的 onChange 发生变化。有没有办法做到这一点?我制作了一个codesandbox,其中包含我想要完成的简单示例

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

最佳答案

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>
)

关于reactjs - React-Select 当值改变时触发 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61614857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com