javascript - 使用reactjs同时点击两个按钮
问题描述
我有 2 个按钮:
<button onClick={click}>Click me</button>
<button>Click me</button>
怎么样,点击click
同时点击第二个按钮?
解决方案
选择第二个按钮元素并使用该HTMLElement.click()
方法模拟鼠标单击该元素。
以下是您可以这样做的方法React.useRef()
:
import React from "react";
function App() {
const secondButtonRef = React.useRef();
const handleFirstButtonClick = () => {
secondButtonRef.current.click();
};
const handleSecondButtonClick = () => {
alert("Second button was clicked.");
};
return (
<div>
<button onClick={handleFirstButtonClick}>Click me 1</button>
<button onClick={handleSecondButtonClick} ref={secondButtonRef}>
Click me 2
</button>
</div>
);
}
或者,如果您无法将 React ref 附加到元素,只需使用document.querySelector
or document.getElementById
。