react-popper的TS错误提示怎么解决?

最近项目在使用react-popper做定位组件
按照官网文档写https://popper.js.org/react-p...
发现一直TS提示错误

import React, { useState } from 'react';
import { usePopper } from 'react-popper';

const Example = () => {
  const [referenceElement, setReferenceElement] = useState(null);
  const [popperElement, setPopperElement] = useState(null);
  const [arrowElement, setArrowElement] = useState(null);
  const { styles, attributes } = usePopper(referenceElement, popperElement, {
    modifiers: [{ name: 'arrow', options: { element: arrowElement } }],
  });

  return (
    <>
      <button type="button" ref={setReferenceElement}>
        Reference element
      </button>

      <div ref={setPopperElement} style={styles.popper} {...attributes.popper}>
        Popper element
        <div ref={setArrowElement} style={styles.arrow} />
      </div>
    </>
  );
};

image.png

看介绍是用了callback ref,但是明明和官网一样的代码,就是跑不起来呢?难道其他人都没有遇到这个问题?

阅读 2k
1 个回答

这用法有问题,ref肯定不能用作setState函数, 用ref

import React, { useState, useRef } from 'react';
import { usePopper } from 'react-popper';

const Example = () => {
  const referenceRef =  useRef();
  const onMountedRefercence =(node)=>{
      referenceRef.current = node
  }

  return (
    <>
      <button type="button" ref={onMountedRefercence}>
        Reference element
      </button>
    </>
  );
};

ref={onMountedRefercence}也可以直接写成ref={referenceRef}

补充:

const Example = () => {
  const [node, setNode] = useState<HTMLButtonElement|null>(null);

  return (
    <>
      <button type="button" ref={setNode}>
        Reference element
      </button>
    </>
  );
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题