显示选定选项中的Div部分-无状态组件

时间:2020-02-01 16:41:42

标签: javascript reactjs redux react-redux

有点新的反应和还原。我试图在用户选择特定选项值后调用/显示部分。该选择将通过API填充(我可以处理),但目前,例如,如果我有以下代码

const Student = ({key}) = > {
  return (
      <React.Fragment>
         <div>
            <select>
                <option value="markJ">Mark J.</option>
                <option value="maryA">Marry A.</option>
                <option value="peterM">Peter M</option>
            </select>
         </div>
         <div id="showThisDiv">
            <input type="text" placeholder="age" />
         </div>
      </React.Fragment>

  );
};
export default Student

例如,如果我要在选择了值maryA的选项后显示ID为#showThisDiv的div,我该如何实现?我正在尝试仅在功能组件中执行此操作。

1 个答案:

答案 0 :(得分:0)

您需要使用状态来存储所选选项。当状态值为maryA时,显示showThisDiv。不必使用id="showThisDiv"

const Student = ({key}) = > {
  const [selected, setSelected] = useState()

  const handleChange = (event) => {
     setSelected(event.target.value)
  }

  return (
      <React.Fragment>
         <div>
            <select value={selected} onChange={handleChange}>
                <option value="markJ">Mark J.</option>
                <option value="maryA">Marry A.</option>
                <option value="peterM">Peter M</option>
            </select>
         </div>
         {selected === 'maryA' && <div id="showThisDiv">
            <input type="text" placeholder="age" />
         </div>}
      </React.Fragment>

  );
};
export default Student

如果需要多个选择,则可以使用下一个代码:

  const Student = ({key}) = > {
  const [selected, setSelected] = useState()

  const handleChange = (event) => {
     const newSelectedOptions = [...event.target.options].filter(o => o.selected).map(o => o.value);
     setSelected(newSelectedOptions)
  }

  return (
      <React.Fragment>
         <div>
            <select value={selected} onChange={handleChange} multiple>
                <option value="markJ">Mark J.</option>
                <option value="maryA">Marry A.</option>
                <option value="peterM">Peter M</option>
            </select>
         </div>
         {selected.includes("maryA") && <div id="showThisDiv">
            <input type="text" placeholder="age" />
         </div>}
      </React.Fragment>

  );
};
export default Student