裁判变更时如何重新呈现 [英] How to rerender when refs change

查看:59
本文介绍了裁判变更时如何重新呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆