我不确定如何解决这个问题,以便在调整屏幕大小时设置新的宽度。当前它无法调整大小: TypeError: el.getBoundingClientRect 不是函数 它在负载时计算正确的宽度,但在调整大小时制动
import React, { useEffect, useCallback, useState, useLayoutEffect } from 'react'
import charts from 'charts'
const Charts = props => {
const
chartRenderers = {
line: charts.d3_line(),
horizontalBar: charts.d3_horizontal_bar(),
tables: charts.d3_table()
},
// https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
useWidth = () => {
const
[width, setWidth] = useState(null),
ref = useCallback(el => {
console.log(el)
if (el !== null) {
setWidth(el.getBoundingClientRect().width);
}
}, []);
useLayoutEffect(() => {
window.addEventListener('resize', ref, false);
return () => {
window.removeEventListener('resize', ref);
}
}, [ref])
return [width, ref];
},
{ component, siteData } = props,
[width, ref] = useWidth();
useEffect(
() => {
const parsedData = component.type === "tables" ? JSON.parse(siteData) : siteData
chartRenderers[component.type].renderChart(
parsedData,
charts.d3.select(`#${component.id}`),
width,
component.height,
component.options
)
}
)
return <div id={component.id} key={component.id} ref={ref}/>
}
export default Charts
当窗口调整大小时,您似乎没有在任何地方调用该函数。尝试将useWidth
实现更改为:
import { useState, useCallback } from 'react';
function useWidth(elementRef) {
const [width, setWidth] = useState(null);
const updateWidth = useCallback(() => {
if(elementRef && elementRef.current) {
const { width } = elementRef.current.getBoundingClientRect();
setWidth(width);
}
}, [elementRef]);
useEffect(() => {
updateWidth();
window.addEventListener('resize', updateWidth);
return () => {
window.removeEventListener('resize', updateWidth);
}
}, [updateWidth])
return [width]
}
用法
import React, { useRef } from 'react';
const Charts = props => {
const ref = useRef(null);
// rest of code
const [width] = useWidth(ref);
// do wherever you want with width
return (
<div ref={ref}/>
)
}