【问题标题】:How do I get the selected value from the select to another component?如何从选择中获取选定的值到另一个组件?
【发布时间】:2021-08-22 05:04:30
【问题描述】:

我有这个选择组件,它们的值取自 useEffect 数据。在这个组件中,我可以在控制台中看到从 select 中选择的值

const SelectName = () => {
  const [value, setValue] = useState(0);
  const [names, setNames] = useState([]);
  const handleChange = (e) => setValue(e.target.value);
  useEffect(() => {
    const unsubscribe = firestore
      .collection("name")
      .onSnapshot((snapshot) => {
        const arr = [];
        snapshot.forEach((doc) =>
          arr.push({
            ...doc.data(),
            id: doc.id,
          })
        );
        setNames(arr);
      });

    return () => {
      unsubscribe();
    };
  }, []);
  //   console.log(value);
  return (
    <div>
      <FormControl fullWidth>
        <InputLabel htmlFor="names">Names</InputLabel>
        <Select onChange={handleChange} fullWidth>
          {names &&
            names.map((user) => (
              <MenuItem
                key={user.firstName + " " + user.lastName}
                value={user.firstName + " " + user.lastName}
                // defaultValue={}
              >
                {user.firstName + " " + user.lastName}
              </MenuItem>
            ))}
        </Select>
      </FormControl>
    </div>
  );
};

export default SelectName;

我有这个带有其他字段的其他组件,我想在这里添加选择组件。但是,我无法在此表单中获取所选组件的值。我也会在这个组件中使用两次选择组件;首先是第一个选定的名称和第二个选定的名称。在某些情况下,用户可能会输入第一个和第二个 select 的不同名称。

我尝试将valueonChange 放在第一个select 组件上,但在控制台中看不到所选值。我如何能够从选择中获取值?谢谢。

  const [value, setValue] = useState("");
  const handleChange = (e) => setValue(e.target.value);
  console.log(value);

      

 <form onSubmit={handleSubmit}>
                  //other fields
                     <Grid item>
                   //1st selected Name
                    <SelectName
                      value={value}
                      onChange={handleChange}
                    />
                  </Grid>
                   <Grid item>
                   //2nd selected Name
                    <SelectName/>
                  </Grid>
                    <ButtonForm type="submit" fullWidth>
                      Submit
                    </ButtonForm>
                  </Grid>
                </Grid>
              </form>

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore material-ui


    【解决方案1】:

    您应该解构传递的valueonChange 属性并使用它们而不是本地的value 组件状态。

    const SelectName = ({ value, onChange }) => {
      const [names, setNames] = useState([]);
    
      useEffect(() => {
        const unsubscribe = firestore
          .collection("name")
          .onSnapshot((snapshot) => {
            const arr = [];
            snapshot.forEach((doc) =>
              arr.push({
                ...doc.data(),
                id: doc.id,
              })
            );
            setNames(arr);
          });
    
        return () => {
          unsubscribe();
        };
      }, []);
    
      return (
        <div>
          <FormControl fullWidth>
            <InputLabel htmlFor="names">Names</InputLabel>
            <Select
              value={value}       // <-- pass value
              onChange={onChange} // <-- pass change handler
              fullWidth
            >
              {names &&
                names.map((user) => (
                  <MenuItem
                    key={user.firstName + " " + user.lastName}
                    value={user.firstName + " " + user.lastName}
                  >
                    {user.firstName + " " + user.lastName}
                  </MenuItem>
                ))}
            </Select>
          </FormControl>
        </div>
      );
    };
    

    作为一种优化,为了进一步概括,您可能还想将 Firestore 逻辑分解到父级中,并将选项作为道具传递。

    【讨论】:

    • 传递valueonChange 确实有效。谢谢你。分解出 Firestore 逻辑意味着什么?
    • @AranyaDream 我的意思是在父级中调用该逻辑一次并将选项传递给SelectName 组件。
    猜你喜欢
    • 2018-08-19
    • 2021-01-08
    • 2014-09-27
    • 2015-07-02
    • 1970-01-01
    • 2017-05-04
    • 2013-02-21
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多