javascript - 如何在 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 标签,但我该怎么做呢?
有任何想法吗?
解决方案
这可以通过 3 个步骤解决:
- 在您的代码库中获取 SVG 图标作为 React 组件。
- 传给
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"
>
...
你完成了!
*要记住的重要一点:子节点仍然是非引用的,所以如果在命中的路上没有形状,它就可以工作。您可以为每个孩子附加一个参考。
推荐阅读
- mysql - Windows中的mysql差异/增量备份
- python - Python 通过 1 次调用设置更多属性
- spring-boot - RequestHandlerRetryAdvice 无法在 Spring Integration 中与 Ftp.outboundGateway 一起使用
- ios - 在 Mapbox iOS SDK 的标记下移动地图
- spring - 当我使用 ng build 时,proxy.conf.json 在 Angular 6 中不起作用
- android - 仅在某些活动中的操作栏?
- ruby-on-rails - 在 Rails 中添加复杂的查询
- python - 试图总结投资金额,但一直说不可迭代
- ansible - 确定演出主持人
- spring - 如何为 Spring Boot 配置服务器设置超时值