【问题标题】:Semantic UI react dropdown: Can you dynamically set the value?语义 UI 反应下拉:你可以动态设置值吗?
【发布时间】:2022-11-09 09:07:55
【问题描述】:

我正在使用来自semantic-ui-react 的下拉列表。语义用户界面下拉列表在我的Artists 组件中,该组件正在使用它的父组件App。

现在下拉列表工作正常,如果您从下拉列表中选择一个名称(艺术家),则调用 handleArtistSelection 函数并将该艺术家的名称传递给它。大部分代码如下。

但是还有另一种方法来设置下拉列表的值吗?例如在 jquery 中你可以使用:

$("#mydropdownlist").val("thevalue").change();

应用组件

export default function App() {

     const handleArtistSelection = (artist) => {
        ...
     };

     const artistOptions = artistArray.map((artist) => { return {text: artist, value: artist} });

     return (
        <div className="App">
          <h1>Explore Music Award Show Winners</h1>
          <Artists options={artistOptions} onArtistChange={handleArtistSelection} placeholder={'Pick an artist'}/>
        </div>
     )

}

艺术家组件:

import {Dropdown} from 'semantic-ui-react';

export default function Artists (props) {

    const handleOnChange = (e, data) => {
        props.onArtistChange(data.value);
    }

    return(
        <Dropdown placeholder={props.placeholder} search selection options={props.options} onChange={handleOnChange}/>
    )
}

【问题讨论】:

    标签: javascript reactjs semantic-ui semantic-ui-react


    【解决方案1】:

    useRef 怎么样,直接在 ref 上调用 setState。

    const countryOptions = [
      { key: "af", value: "af", flag: "af", text: "Afghanistan" },
      { key: "ax", value: "ax", flag: "ax", text: "Aland Islands" },
      { key: "al", value: "al", flag: "al", text: "Albania" },
      { key: "dz", value: "dz", flag: "dz", text: "Algeria" }
    ];
    
    const DropdownExampleSearchSelection = () => {
      const ref = React.useRef(null);
      const handleClick = () => {
        ref.current.setState({ value: "dz" });
      };
      return (
        <>
          <Dropdown
            ref={ref}
            placeholder="Select Country"
            fluid
            search
            selection
            options={countryOptions}
          />
          <hr />
          <Button type="button" onClick={handleClick}>
            Select Algeria
          </Button>
        </>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2018-10-12
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多