1 回答
TA贡献1776条经验 获得超12个赞
您可能希望使用字典作为对象,将给定键 映射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'));
添加回答
举报