簡體   English   中英

多個打字稿<Select>onChange 處理程序

[英]Multiple Typescript <Select> onChange handler

首先讓我說我不是 TS 開發人員。 所以如果我提出一個愚蠢的問題,請告訴我。
我正在嘗試使用多項選擇,基本上我需要多個下拉菜單。
從material-ui中的簡單選擇開始,我嘗試向前發展。

我使它與單個選擇一起工作,我的問題是我不明白如何使用onChange事件添加新選擇

type OnChangeValue = {
  locationNaming: unknown;
};

interface ServerNamingDropdownProps {
  onChange(value: OnChangeValue): void;
  error?: boolean | undefined;
  initialValue?: string | undefined;
}

export const ServerNamingDropdown: React.FC<ServerNamingDropdownProps> = ({
  onChange,
  error,
  initialValue = undefined,
}) => {

  const [locationNamingSelected, setLocationNaming] = useState(
    initialValue ? initialValue : '',
  );

  return (
    <div>
      <FormControl sx={{ minWidth: 120 }}>
        <InputLabel id="demo-simple-select-label">Location</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={locationNamingSelected || ''}
          label="Location"
          error={error}
          labelWidth={140}
          style={{ width: 300 }}
          onChange={e => {
            onChange({
              locationNaming: e.target.value,
            });
            setLocationNaming(e.target.value as string);
          }}        >
          {location.map(item => (
            <MenuItem value={item.abbreviation} key={item.key}>
              {item.name}
            </MenuItem>
          ))}
        </Select>
    </div>
  );
};

我必須為部門添加一個新的下拉列表。
我知道應該將departmentNaming添加到OnChangeValue中。
但我不明白如何管理onChange

任何想法將不勝感激。

謝謝

當你改變你的狀態時,React 將重新運行你的渲染,即當你調用setLocationNaming時。 此時渲染函數的輸出應該不同。 正如@mstephen19 所說,您的函數返回的內容可能取決於 props或 state 這是一個非常簡單(未經測試)的草圖:

const MyConditionalRender = () => {
  const [showMoreContent, setShowMoreContent] = useState(false);

  return (
    <div>
      <button onClick={() => setShowMoreContent(true)}>Show</button>
      {showMoreContent && (
        <p>More Content, like an extra dropdown for the department.</p>
      )}
    </div>
  );
};

請閱讀 mstephen19 鏈接的條件渲染文檔。

暫無
暫無

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

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