reactjs 如何使用react js创建一个下拉菜单这是一个设置一个值的权利这之后如何处理这个

monwx1rj  于 2023-03-12  发布在  React
关注(0)|答案(2)|浏览(108)
const [selectedDepartment, setSelectedDepartment] = useState("");

  const DepartmentDropdown = () => {
    const handleSelectChange = (event) => {
      setSelectedDepartment(event.target.value);
    };

    const handleSubmit = (e) => {
      e.preventDefault();
      console.log(email);
    };
      return(
          <div>
            <label htmlFor="departments">Select a Department:</label>
            <select
              id="departments"
              value={selectedDepartment}
              onChange={handleSelectChange}
            >
              <option value="">--Select a Department--</option>
              <option value="ai&ds">AI&DS</option>
              <option value="cse">CSE</option>
              <option value="ece">ECE</option>
              <option value="eee">EEE</option>
              <option value="it">IT</option>
              <option value="mech">MECH</option>
            </select>
            {selectedDepartment && <p>You selected: {selectedDepartment}</p>}
          </div>)

}

在这里,我有一个疑问,我应该在哪里使用调用函数DepartmentDropdown。如何访问这个下拉菜单。有没有其他最简单的方法来实现这一点。

anauzrmj

anauzrmj1#

不要在DepartmentDropdown组件中创建状态,而是在父组件中创建状态,您将从父组件调用DepartmentDropdown

const DepartmentDropdown = ({handleSelectChange,selectedDepartment}) => {

    return (
      <div>
        <label htmlFor="departments">Select a Department:</label>
        <select
          id="departments"
          value={selectedDepartment}
          onChange={(event) => {
            handleSelectChange(event.target.value)
         }}
        >
          <option value="">--Select a Department--</option>
          <option value="ai&ds">AI&DS</option>
          <option value="cse">CSE</option>
          <option value="ece">ECE</option>
          <option value="eee">EEE</option>
          <option value="it">IT</option>
          <option value="mech">MECH</option>
        </select>
        {selectedDepartment && <p>You selected: {selectedDepartment}</p>}
      </div>
    );
 
};

如代码中所示

DepartmentDropdown = ({handleSelectChange,selectedDepartment}) =>

handleSelectChangeselectedDepartment将作为 prop 传递给DepartmentDropdown组件
现在,在父组件中创建selectedDepartment,然后将其传递给DepartmentDropdown以使其能够显示
并创建handleSelectChange,然后将其传递给DepartmentDropdown,以使其能够更新父组件中的selectedDepartment状态:

const Parent = () => {
  
    const [selectedDepartment, setSelectedDepartment] = useState("");
    const handleSelectChange = (value) => {
        setSelectedDepartment(value);
      };
     //...
      return (
        <>
         //... 
        <DepartmentDropdown handleSelectChange={handleSelectChange} selectedDepartment={selectedDepartment} />
         //... 
        </>
      )
}
a0x5cqrl

a0x5cqrl2#

对于React函数组件,您可以使用函数的名称作为JSX中的组件名称,如下所示:

<DepartmentDropdown />

这看起来很奇怪,因为它是一个用作元素名的函数,但这就是JSX的工作方式。

相关问题