我想在具有动态渲染元素的功能组件中包含引用。
请帮助我使用以下命令创建动态参考useRef
挂钩并在处理程序中访问它。
-
需要创建3个useRef
s 指向 3 个按钮。
-
使用“ref1.value”或“ref2.value”等在按钮处理程序中访问它们。
let abc=[1,2,3];
function submitclick(){
alert(123);
}
// Here I want to access the buttons using the refs
return ( <div>
{ abc.map(function(index){ return (<button ref='123' onClick={submitclick}>{`Button${index}`}</button>)})}
</div>);
};
ReactDOM.render(<MyComponent name="doug" />, document.getElementById('root'));```
ref
s 基本上是对象,并且它们有一个默认键current
。因此,您可以创建一个数组refs
像这样:
const myRefs= useRef([]);
然后你可以像这样填充这个引用数组:
ref={el => (myRefs.current[i] = el)}
这是完整版本:
{
[1, 2, 3].map((v, i) => {
return (
<button
ref={(el) => (myRefs.current[i] = el)}
id={i}
onClick={submitClick}
>{`Button${i}`}</button>
);
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)