【问题标题】:How to insert properties and functions inside ref?如何在 ref 中插入属性和函数?
【发布时间】:2020-12-05 15:06:42
【问题描述】:

如何在 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} />
    )
}

我该怎么做?

【问题讨论】:

    标签: javascript reactjs ref


    【解决方案1】:

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

    你不能在函数组件上使用 ref 属性,因为它们没有实例。

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

    要使您的示例正常工作,您需要将 &lt;MyComponent /&gt; 转换为 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多