反应“ useRef”:无法访问.current中的方法

时间:2020-03-30 08:34:14

标签: reactjs react-native react-hooks use-ref

因此,在我的React Native应用程序中,我想按照this的指导集成here滑块。

问题是,我想访问setLowValue()的{​​{1}}属性的方法.current,正如在the guidance website末尾所指定的那样。我将useRef()打印到控制台,看到.current被指定为函数,因此肯定存在。为什么我不能访问它?

这是我的代码:

setLowValue()

我们将不胜感激!

3 个答案:

答案 0 :(得分:3)

首先在'componentDidMount'和'componentDidUpdate'生命周期状态上设置ref值,这两个状态均在第一次渲染之后出现。

日志记录可能引起混乱的原因是,日志可以/将在第一个渲染(在componentDidMount之前,具有初始参考电流)和之后(具有正确定义的ref.current,都通过ref'd设置)发生组件)。

这里的解决方案是在安装组件之后访问ref,这可以通过useEffect挂钩来实现。

请参阅:https://reactjs.org/docs/refs-and-the-dom.html

tldr:

useEffect(() => {
  console.log(slider.current.initialLowValue);
}, [])

答案 1 :(得分:2)

我建议将初始参考设置为null

const Slider: React.FC<Props> = ({size, setSize}) => {

  const slider = useRef(null);

  console.log('slider ', slider.current); // null

  useEffect(() => {
    if (slider.current) {
      console.log('slider ', slider.current.initialLowValue); // size
    }
  }, []);

  return (
    <View style={styles.container}>
      <RangeSlider
        ref={slider}
        max={70}
        min={50}
        step={1}
        initialLowValue={size} // I want to have access to this property
        value={size}
        onValueChanged={value => setSize({size: value})}
      />
    </View>
  );
};

答案 2 :(得分:-1)

尝试一下

 <RangeSlider
      ref={(input) => { this.slider = input; }}
    .......
/>