动态获取功能组件的 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,我可以轻松地做我想做的事。


牧羊人nacy
浏览 305回答 1
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 }) => {&nbsp; const ref = useRef({ first: undefined, second: undefined, third: undefined });&nbsp; const handleClick = () => {&nbsp; &nbsp; const coolRef = ref.current[targetRef];&nbsp; &nbsp; console.log(coolRef);&nbsp; };&nbsp; return (&nbsp; &nbsp; <div ref={node => (ref.current.first = node)}>&nbsp; &nbsp; &nbsp; <div ref={node => (ref.current.second = node)}>&nbsp; &nbsp; &nbsp; &nbsp; <div ref={node => (ref.current.third = node)}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button onClick={handleClick}>Find Ref and Do Something</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>&nbsp; );};const App = () => {&nbsp; return <RefContainer targetRef="third" />;};ReactDOM.render(<App />, document.getElementById('root'));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript