javascript - 动态获取功能组件的 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
,我可以轻松地做我想做的事。
解决方案
您可能希望使用字典作为对象,将给定键映射 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'));
推荐阅读
- maven - 如何在 Maven 中按名称包含/排除 JUnit 5 `ParameterizedTest`
- ios - 如何快速填充图案图像的颜色?
- css - 内联动画样式在 Reactjs 中不起作用
- python - 基于范围列表过滤数据框
- swift - 和 (&&) 迅速的逻辑
- node.js - 如何摆脱“TypeError:req.pipe 不是函数”nestjs 和 fastify
- javascript - 做出反应。将数据从 textarea 传输到数组 JSON
- ios - 如何在 RxSwift 中使用 flatMap 观察上层 Observable?
- javascript - MobX 状态树异步操作和重新渲染 React 组件
- jquery - 知道如何在其他圈子上添加一些延迟