首页 > 解决方案 > 使用 forwardRef 中的 ref 时,ref.current 始终未定义

问题描述

import React, { useRef } from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "left"
};

const Wrapper = () => {
  const ref = useRef();
  return <App ref={ref} />;
};

const App = React.forwardRef(
  ({ placeHolder, onNameSelected, error, onSuggestion }, ref) => {
    ref.current.setAttribute("he-de-data", "");

    return (
      <div style={styles}>
        <h4>Username</h4>
        <input ref={ref} />
      </div>
    );
  }
);

render(<Wrapper />, document.getElementById("root"));

这是一个可以帮助您的沙箱:

我有以下代码,但 ref.current 未定义。我需要使用 refforwardRef并使用该 ref 向 DOM 添加一些属性。但是,ref.current始终是undefined。有什么特别的原因吗?

标签: reactjs

解决方案


首先,您错误地使用了 ref 和 forwardRef 。

使用 forwardRef 是因为无法实例化功能组件,因此如果您将 ref 分配给您创建的任何功能组件,它将为空。forwardRef 所做的是将 ref 转发到它正在包装的组件,然后您可以将其分配给组件内的任何 html 元素,在那里您可以从PARENT访问 DOM 。

您要做的是从组件本身而不是父级中设置属性。所以不需要前向参考

 const Comp =({ placeHolder, onNameSelected, error, onSuggestion }) => {
       const inputRef = useRef(null);
       useEffect(()=>{
          if(inputRef.current!==null)
          inputRef.current.setAttribute("he-de-data", "");
        },[]);

    return (
      <div style={styles}>
        <h4>Username</h4>
        <input ref={inputRef} />
      </div>
    );
  }

https://codesandbox.io/embed/react-16-v0kn4?fontsize=14&hidenavigation=1&theme=dark


推荐阅读