将变量作为参考名称传递

时间:2021-04-06 22:13:17

标签: reactjs

我正在尝试从哈希中提取引用名称并将其传递给 scrollIntoView 而不使用大小写/开关。

建议如何实现这种简单/最好的方法?

Full working code with comments here.

愚蠢但有效

  useEffect(() => {
    if (props.location.hash) {
      switch (props.location.hash.slice(1)) {
        case "targetOne":
          return targetOne.current.scrollIntoView({
            behavior: "smooth"
          });
        case "targetTwo":
          return targetTwo.current.scrollIntoView({
            behavior: "smooth"
          });
        default:
          return null;
      }
    }
  }, [props.location.hash]);

“想法”

useEffect(() => {
if (props.location.hash) {
 props.location.hash.slice(1).current.scrollIntoView({
  behavior: "smooth"
  });
 }
  }, [props.location.hash]);

1 个答案:

答案 0 :(得分:1)

将所有可滚动引用存储在一个包含对象的 useRef 中:

const scrollRefs = useRef({});

将功能性引用设置器传递给需要可滚动的元素。示例:

<div ref={el => scrollRefs.current["targetOne"] = el}>
    <h2>Target One box</h2>
    ....
</div>

现在您可以在 ref 对象中通过哈希名称查找元素:

useEffect(() => {
  if (props.location.hash) {
    const hash = props.location.hash.slice(1);
    const ref = scrollRefs.current[hash];
    ref && ref.scrollIntoView({behavior: "smooth"});
  }
}, [props.location.hash]);
相关问题