【问题标题】:React "useRef": no access to method in .current反应“useRef”:无法访问 .current 中的方法
【发布时间】:2020-07-10 14:18:56
【问题描述】:

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

问题是,我想访问useRef() 的.current 属性的方法setLowValue(),正如在the guidance website 的末尾所指定的那样。我将.current 打印到控制台并看到setLowValue() 被指定为一个函数,所以它肯定存在。为什么我无法访问它?

这是我的代码:

imports ... 

type Props = {
  size: number;
  setSize: (size: SizeState) => void;
};

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

  const slider = useRef(66); // set slider to inital value
  console.log('slider ', slider.current.initialLowValue); // doesn't work: "slider.current.initialLowValue is not a function"

  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>
  );
};

function mapStateToProps(state: RootState) {
  return {
    height: state.sizeResult.size,
  };
}

const mapDispatchToProps = {
  setSize,
};

export default connect(mapStateToProps, mapDispatchToProps)(Slider);

我们将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 不是类组件,问题不在ref=
    【解决方案2】:

    ref 值首先在“componentDidMount”和“componentDidUpdate”生命周期状态上设置,这两个状态都发生在第一次渲染之后。

    日志记录可能导致混淆的原因是日志可以/将在第一次渲染(在 componentDidMount 之前,使用初始 ref.current)和之后(使用正确定义的 ref.current,通过 ref'd 设置组件)。

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

    见:https://reactjs.org/docs/refs-and-the-dom.html

    tldr:

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

    【讨论】:

      【解决方案3】:

      我建议将初始 ref 设置为 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>
        );
      };
      
      

      【讨论】:

        猜你喜欢
        • 2020-02-06
        • 2021-07-03
        • 2020-09-24
        • 2014-11-18
        • 1970-01-01
        • 1970-01-01
        • 2019-12-12
        • 2021-06-28
        • 1970-01-01
        相关资源
        最近更新 更多