【问题标题】:Get the ref of a functional component dynamically - ReactJS动态获取功能组件的 ref - ReactJS
【发布时间】:2019-11-22 18:22:45
【问题描述】:

我需要使用从 props 传递并包含我想要获取的 ref 名称的字符串变量来访问我的 ref。像这样:

function MyComponent(props) {

    const myFirstRef = useRef();
    const mySecondRef = useRef();
    const myThirdRef = useRef();

    function handleClick() {
        const targetRef = props.targetRef;

        // The `targetRef` is a string that contains
        // the name of the one of the above refs!
        // I need to get my ref by string
        // ...
    }

    return (
        <div ref={myFirstRef}>
            <div ref={mySecondRef}>
                <div ref={myThirdRef}>
                    <button onClick={handleClick}>Find Ref and Do Something</button>
                </div>
            </div>
        </div>
    )

}

targetRef 是一个字符串,其中包含上述引用的名称!

在类组件中有this.refs,我可以轻松地做我想做的事。

【问题讨论】:

  • 您可以将您的 refs 保存到单个对象中,并使用不同的键作为它的名称。然后您可以使用对象表示法访问您的 ref

标签: javascript reactjs react-hooks


【解决方案1】:

您可能希望使用字典作为映射给定 targetRef 特定引用的对象:

const ref = useRef({ first: undefined, second: undefined, third: undefined });
ref.current[targetRef];
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';

const RefContainer = ({ targetRef }) => {
  const ref = useRef({ first: undefined, second: undefined, third: undefined });

  const handleClick = () => {
    const coolRef = ref.current[targetRef];
    console.log(coolRef);
  };

  return (
    <div ref={node => (ref.current.first = node)}>
      <div ref={node => (ref.current.second = node)}>
        <div ref={node => (ref.current.third = node)}>
          <button onClick={handleClick}>Find Ref and Do Something</button>
        </div>
      </div>
    </div>
  );
};

const App = () => {
  return <RefContainer targetRef="third" />;
};

ReactDOM.render(<App />, document.getElementById('root'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 2017-10-09
    • 2020-12-04
    • 2021-07-21
    • 2020-11-18
    • 1970-01-01
    • 2021-09-26
    • 2019-12-11
    相关资源
    最近更新 更多