我有带有文本的组件。它通过鼠标单击更改组件自身的状态。但我想保存通过长按选择和复制的可能性。有办法做到吗?重新渲染组件后将重置选择。代码示例:
const App = () => {
const [someState, setSomeState] = React.useState(0);
const clickHandler = () => {
setSomeState(someState + 1);
}
return (
<div
className="App"
onClick={clickHandler}
>
{'State ' + someState}
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
最佳答案
您自己使用 onMouseDown
和 onMouseUp
事件并计算用户单击所用的时间(而不是使用 onClick
)怎么样?
例如,您可以执行以下操作:
const App = () => {
const [someState, setSomeState] = React.useState(0);
const [timeDown, setTimeDown] = React.useState(-1);
const clickHandler = () => setSomeState(someState + 1);
const handleMouseDown = () => setTimeDown(Date.now()); // Save the time of the mousedown event
const handleMouseUp = () => {
const timeUp = Date.now();
const timeDiff = timeUp - timeDown; // Calculate the time the user took to click and hold
if (timeDiff < 1000) { // If it's shorter than 1000ms (1s) execute the normal click handler
clickHandler();
} else { // Execute some other logic, or just ignore the click
// handleLongClick();
}
};
return (
<div
className="App"
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
>
{"State " + someState}
</div>
);
};
您可以找到一个快速的codesandbox作为演示here
关于javascript - react 保存使用重新渲染组件选择文本的可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60563190/