reactjs - React UseRef 的当前值既是初始值,也是我期望的元素
问题描述
我正在尝试设置使用useRef
钩子来设置 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>
);
};
解决方案
ref 没有分配,因此在组件完全安装之前无法正确访问。我最终使用 useEffect 来获取价值。
推荐阅读
- mysql - NodeJs 异步库:为什么发生错误后没有触发回调?
- excel - 是否有公式可以计算并将 h:mm:ss 格式化为 mmm:ss?
- python - 使用附加列对 DataFrame 进行分组和旋转以获取计数比率
- sql - 带有 SQL 的 Excel VBA:指定 Where 子句时不返回行
- python - Plotly-Dash Graph - 显示在形状后面的文本注释
- jsonnet - jsonnet - 从数组中删除空值
- regex - 如何为字符串在正则表达式中包含引号的两个组捕获两种模式(如果存在)
- c# - 使用 DirectLine SDK 和 Xamarin 的高延迟(2-4 秒)机器人响应时间
- python - 在熊猫数据框中移动数据
- python - 在 python 中运行 adb 管道命令