gpt4 book ai didi

reactjs - 如何在功能组件中创建动态引用 - 使用 useRef Hook

转载 作者:行者123 更新时间:2023-12-02 08:00:39 33 4
gpt4 key购买 nike

我想在具有动态呈现元素的功能组件中使用 refs。

请帮助我使用 useRef Hook 创建动态 Refs 并在处理程序中访问。

1) 需要创建 3 个 useRefs 来指向 3 个按钮。

2)使用“ref1.value”或“ref2.value”等在按钮处理程序中访问它们

    let abc=[1,2,3];
function submitclick(){
alert(123);
// Here i want to access the buttons with 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([]);

然后你可以像这样填充这个 refs 数组:
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>
);
});
}

关于reactjs - 如何在功能组件中创建动态引用 - 使用 useRef Hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810378/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com