【问题标题】:useRef object returning undefined in React/React-Native在 React/React-Native 中返回 undefined 的 useRef 对象
【发布时间】:2019-09-15 01:23:31
【问题描述】:

当我尝试访问 ref 对象时,我收到了undefined。我正在映射一组图像并尝试通过 useRef 访问单个图像。

首先,我将useRef初始化如下:

const gridImages = useRef([React.createRef(), React.createRef()])

然后是图像的映射:

<View style={styles.grid}>
    {images.map((src, index) => {
        const style = index === activeIndex ? activeIndexStyle : undefined
        return (
            <TouchableWithoutFeedback key={index} onPress={() => handleOpenImage(index)}>
                <Animated.Image 
                    source={{ uri: src }}
                    style={[ styles.gridImage, style ]}
                    ref={gridImages.current[index]}
                />
            </TouchableWithoutFeedback>
        )
    })}
</View>                

当我调用以下方法时,我收到一条错误消息

undefined 不是一个对象(评估 'gridImages.current[index].getNode')

当我console.log 对象gridImages.current 显示没有问题的方法时,但只要我包含index,我就会得到undefined 错误。

const handleOpenImage = index => {
    console.log(gridImages.current[index])
    gridImages.current[index].getNode().measure((x, y, width, height, pageX, pageY) => {
        position.setValue({
            x: pageX,
            y: pageY,
        })

        size.setValue({
            x: width,
            y: height,
        })
        setActiveImage(images[index])
        setActiveIndex(index)
    })
}

【问题讨论】:

    标签: javascript reactjs react-native react-hooks


    【解决方案1】:

    我认为问题在于您需要在索引后添加另一个 .current

    例如:gridImages.current[index].current,因为您同时使用 useRefReact.createRef

    这是一个仅包含关键部分的简化代码示例(请原谅转换为 ReactDOM 而不是 React Native,但原理应该仍然相同)

    function Comp(props) {
      const { images } = props;
      const gridImages = React.useRef(images.map(_ => React.createRef()));
    
      const handleClick = index => {
        console.log(gridImages.current[index].current);
      };
    
      return (
        <div>
          {images.map((src, index) => (
            <img
              onClick={() => handleClick(index)}
              src={src}
              key={index}
              ref={gridImages.current[index]}
            />
          ))}
        </div>
      );
    }
    
    function App() {
      return (
        <Comp
          images={[
            "https://placekitten.com/100/100",
            "https://placekitten.com/101/101",
            "https://placekitten.com/102/102"
          ]}
        />
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <div id="root"></div>

    请注意,我还根据图像的数量将useRef 部分更新为动态的,因为这似乎是动态的,在此答案中建议:https://stackoverflow.com/a/55996413/2690790

    【讨论】:

    • 你是对的!你能再解释一下images.map(_ =&gt; React.createRef())吗?我是 useRef 的新手,如果我理解正确,我们正在映射图像并创建引用作为 gridImages 的初始值?
    • @Kevvv 是的。如果您知道您将始终只有两个图像,那么您提供的代码将可以正常工作!这将处理 0 到 n 现在的图像(假设这是动态的)。注意:如果图像数量更改,这仅适用于useRef 的初始值。基于这个问题:stackoverflow.com/q/55995760/2690790
    • 如果通过images.map(_ =&gt; React.createRef()) 为图像分配了引用,那么当ref={gridImages.current[index]} 发生在divimg 中时究竟发生了什么?
    • 图像未分配images.map(_ =&gt; React.createRef()),正在为每个图像实例化(创建)一个引用,因此我们拥有与图像一样的引用数量。然后在ref={gridImages.current[index]},React,内部大致在做ref={gridImages.current[index]}.current = thisImageReference,所以稍后我们可以通过gridImages.current[index]}.current访问它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多