【发布时间】: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