首页 > 解决方案 > 动态获取功能组件的 ref - ReactJS

问题描述

我需要使用从 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,我可以轻松地做我想做的事。

标签: javascriptreactjsreact-hooks

解决方案


您可能希望使用字典作为对象,将给定键映射 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'));

编辑 react-antd-styled-template


推荐阅读