繁体   English   中英

如何从 function 返回之前定义的 useRef 变量?

[英]How can I return a useRef variable, defined before, from a function?

我正在渲染一个列表。 在特定按钮上,我想要一个参考。 有没有办法存档? 或者有什么解决办法?

const plusParent = useRef(null);
const plusChild = useRef(null);
const minusParent = useRef(null);
const minusChild = useRef(null);

const detectRef = (button, comp) => {
    switch (button) {
      case '+':
        return comp === 'parent' ? plusParent : plusChild;
      case '-':
        return comp === 'parent' ? minusParent : minusChild;
    }
  };

{row.map((button) => {
          return (
            <View>
              <TouchableOpacity
                 ref={() => detectRef(button, 'parent')}
                >
                <Text>{button}</Text>
              </TouchableOpacity>
            </View>
          );
        })}

如果我尝试访问我的一个 useRef 变量,我将得到 null。

目前,您的ref最终成为匿名箭头 function 只需删除额外的 function 包装器并直接调用 function 以返回结果。

{row.map((button) => {
          return (
            <View>
              <TouchableOpacity
                 ref={detectRef(button, 'parent')}
                >
                <Text>{button}</Text>
              </TouchableOpacity>
            </View>
          );
        })}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM