首页 > 解决方案 > React UseRef 的当前值既是初始值,也是我期望的元素

问题描述

我正在尝试设置使用useRef钩子来设置 div 的引用,但似乎一旦找到引用,该值就不会更新。下面怎么可能?

当前为 0 和 div

    const SelectDropDown = props => {
    const { helperText, label, ...restProps } = props;
    const [animals, setAnimals] = React.useState('');
    const labelRef = useRef(0);

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

     console.log('ref', labelRef);

   return (
   <FormControl>
      <div ref={labelRef}></div>
     <InputLabel id={`label-${label}`}>Animals</InputLabel>
        <MSelect
        autoWidth
        labelId={`label-${label}`}
        id="demo-simple-select"
        value={animals}
        onChange={handleChange}
        >
        {options.map(option => {
         return <MenuItem value={option.id}>{option.value}</MenuItem>;
         })}
         </MSelect>
        </FormControl>
      );
   };

标签: reactjs

解决方案


ref 没有分配,因此在组件完全安装之前无法正确访问。我最终使用 useEffect 来获取价值。


推荐阅读