首页 > 解决方案 > 如何在 React 中将 Ref 传递给 SVG 组件

问题描述

我有一个 svg 组件,它的声明如下:


import {ReactComponent as Icon} from 'someplace.svg'

function SomeComponent(props){
   const [someState, setSomeState] = useState(0)
   const iconRef = useRef(null)

   useEffect(() => {
      //always prints null
      console.log(iconRef.current) 
   }, [someState])

return <div>
 <button onClick={() => setSomeState(prev => prev + 1)}>{someState}</button>
 <Icon ref={iconRef}/>
</div>
}

这里的问题是 iconRef 将始终返回 null。我认为这是因为它被声明为组件,因此需要将 ref 直接转发到 svg 标签,但我该怎么做呢?

有任何想法吗?

标签: javascriptreactjssvg

解决方案


这可以通过 3 个步骤解决:

  1. 在您的代码库中获取 SVG 图标作为 React 组件。
  2. 传给setRef它。

例子:

将 SVG 代码抓取到组件中,如下所示:

const CloseIcon = (props) => (
  <svg
    width="38"
    height="38"
    viewBox="0 0 38 38"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <circle cx="19" cy="19" r="18" stroke="#AFAFAF" stroke-width="2"></circle>
    <path
      d="M13.0548 13.336L24.9868 25.9185"
      stroke="#AFAFAF"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
    ></path>
    <path
      d="M24.9862 13.3365L13.0542 25.9189"
      stroke="#AFAFAF"
      stroke-width="2"
      stroke-linecap="round"
      stroke-linejoin="round"
    ></path>
  </svg>
)

export default CloseIcon

然后,在使用此图标的父组件中,设置其 ref 属性,例如:


...

const closeIconRef = createRef()
...

<CloseIcon
   style={{ position: 'absolute', top: 18, right: 18, cursor: 'pointer' }} 
   setRef={closeIconRef}
/>

然后setRef在 SVG 组件中添加标签:

const CloseIcon = ({ setRef }) => (
  <svg
    ref={setRef}
    width="38"
    height="38"
    viewBox="0 0 38 38"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
...

你完成了!

*要记住的重要一点:子节点仍然是非引用的,所以如果在命中的路上没有形状,它就可以工作。您可以为每个孩子附加一个参考。


推荐阅读