Sum*_*dey 13 reactjs react-hooks
我想在具有动态呈现元素的功能组件中使用 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'));```
Run Code Online (Sandbox Code Playgroud)
use*_*899 33
ref
s 基本上是对象,它们有一个默认键current
。所以,你可以创建一个这样的数组refs
:
const myRefs= useRef([]);
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样填充这个 refs 数组:
ref={el => (myRefs.current[i] = el)}
Run Code Online (Sandbox Code Playgroud)
这是完整版:
{
[1, 2, 3].map((v, i) => {
return (
<button
ref={(el) => (myRefs.current[i] = el)}
id={i}
onClick={submitClick}
>{`Button${i}`}</button>
);
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6381 次 |
最近记录: |