为什么在useEffect中ref.current的值一直是null?

项目中用到XTermjs,用了三方包装的组件,想在组件初始化之后,做一些事情,比如调用terminal.focus()聚焦

想到了用useEffect来实现如下

image.png

问题是,在这里面打印termRef.current的值一直是null,所以不会调用到terminal.focus()

这里应该怎么实现呢?把termRef.current传入到useeffect的依赖项里面去吗?

阅读 4.5k
2 个回答

实测不会啊,是不是XTerm实现的问题?

import React, { useEffect } from 'react'

export default function APp() {
  const ref = React.useRef<Handler>(null)
  useEffect(() => {
    console.log(ref.current)
    if (ref && ref.current) {
      ref.current.focus()
    }
  }, [])

  return <div>
    <p>parent</p>
    <Child ref={ref} />
  </div>
}

interface Handler {
  focus: () => void;
}

const Child = React.forwardRef(function Child(props, ref) {
  React.useImperativeHandle(ref, () => {
    return {
      focus: () => {
        console.log('child focus')
      }
    }
  })
  return <div>child</div>
})

image.png

更新

更换为类组件依然没有问题

import React, { useEffect } from 'react'

export default function App() {
  const ref = React.useRef(null)
  useEffect(() => {
    console.log(ref.current)
    if (ref && ref.current) {
      ref.current.focus()
    }
  }, [])

  return <div>
    <p>parent</p>
    <Child2 ref={ref} />
  </div>
}

interface Handler {
  focus: () => void;
}

class Child2 extends React.Component<any, Handler> {
  public focus = () => {
    console.log('child focus', this.el)
  }

  public el: HTMLDivElement | null = null

  public render = () => {
    return <div ref={(el) => this.el = el}>child</div>
  }
}

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题