如何在 ref 中插入属性和函数?

How to insert properties and functions inside ref?

如何在引用中插入属性和函数?像这个例子:

const MyComponent = () => {

    const [loading, setLoading] = React.useState(false)
    const onTest = () => 'works'

    return (
        <div {...props}>
    )
}

那么我想这样使用属性 loading 和函数 onTest:

const Test = () => {

    const myRef = React.useRef()

    React.useEffect(() => {

        if (myRef.current)
            alert('loading is ' + myRef.current.loading + ' function is ' + myRef.current.onTest())
    })

    return(
        <MyComponent ref={myRef} />
    )
}

我该怎么做?

您无法在功能组件上设置 ref,因为它们没有实例。

You may not use the ref attribute on function components because they don’t have instances.

(source: https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs)

为了使您的示例正常工作,您需要将 <MyComponent /> 转换为 class component

const Test = () => {
  const myRef = React.useRef();

  React.useEffect(() => {
    if (myRef.current)
      console.log(
        "loading is " +
          myRef.current.state.loading +
          " function is " +
          myRef.current.onTest()
      );
  });

  return <MyComponent ref={myRef} />;
};

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  onTest() {
    return "works";
  }

  render() {
    return <h1>MyComponent</h1>;
  }
}

ReactDOM.render(<Test />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>