首页 > 解决方案 > 为什么 ref 总是为空?

问题描述

我在下面有一个组件,在第一次渲染时我有正确ref的输入,但是我总是得到null,下一次渲染,请告诉我为什么?ref通过 props 传递给 input:

const inputRef = useRef(null);
useEffect(() => {
  setTimeout(() => {
    if (inputRef.current) {
        inputRef.current.focus();
    }
  });
 }, [inputRef]);

render() {
  return(
    <div>
      <FirstComponent />
      {({ selectedItem, items }) => (
             <SecondCompontnt
                inputRef={inputRef}
                items={items}
                onSelect={onSelect}
                value={selectedItem}
              />
          )}
    </div>
  )
}

标签: javascriptreactjs

解决方案


一旦您ref在其一个子组件的父组件中拥有了 ,那么您需要应用所谓的Forwarding Ref 技术,如文档所述:

Ref 转发是一种通过组件自动将 ref 传递给它的一个子组件的技术。对于应用程序中的大多数组件,这通常不是必需的。

假设您在父组件中具有以下内容:

const childDivRef = useRef(null);

return <>
  <ChildComponent ref={childDivRef} />
</>

然后你需要在子组件中有如下:

import React, { forwardRef } from 'react';

const ChildComponent = forwardRef((props, ref) => {
    return <div ref={ref} className="child-component">
        <h3>Child component</h3>
    </div>
})

如果您需要一个工作示例,请找到我之前创建的这个 GitHub 存储库:https ://github.com/norbitrial/react-forwarding-ref-example

我希望这有帮助!


推荐阅读