裁判变更时如何重新呈现 [英] How to rerender when refs change
问题描述
代码:
import DrawControl from "react-mapbox-gl-draw";
export default function MapboxGLMap() {
let drawControl = null
return(
<DrawControl ref={DrawControl => {drawControl = DrawControl}}/>
)
}
我想在 drawControl
不为null时加载数据.我检查了可能使用回调引用的文档.
I want to load data when the drawControl
not null. I check the document that may use callback ref.
那么,如何监听 drawControl
的更改并加载数据?
So, how do I listen the drawControl
changes and load data?
推荐答案
如果要在ref更改后触发重新渲染,则必须使用 useState
而不是 useRef 代码>.只有这样,您才能确保组件将重新渲染.例如:
If you want to trigger a re-render after the ref changes, you must use useState
instead of useRef
. Only that way can you ensure that the component will re-render. E.g.:
function Component() {
const [ref, setRef] = useState();
return <div ref={newRef => setRef(newRef)} />
}
如 useRef 文档中所述:
请记住,当内容更改时,
useRef
不会通知您.更改.current
属性不会导致重新渲染.如果您想在React将引用附加或分离到DOM节点时运行一些代码,则可能要使用
Keep in mind that
useRef
doesn’t notify you when its content changes. Mutating the.current
property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
It may sometimes be better to store whatever value you are getting from the DOM node, as suggested here, instead of storing the node itself.
这篇关于裁判变更时如何重新呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!