我想在 <input type='file'...>
时显示自定义警告消息单击,然后让浏览器通过单击“确认”按钮启动文件选择对话框。这是为了确保用户正确了解警告消息。可能吗?
import React from "react";
import "./styles.css";
export default function App() {
const [warn, setWarn] = React.useState(false);
const inputRef = React.useRef();
const handleChange = e => {};
const handleClick = e => {
if (!warn) {
setWarn(true);
e.preventDefault();
}
};
const handleContinue = e => {
const event = new Event("input", { bubbles: true });
inputRef.current.dispatchEvent(event);
};
return (
<div className="App">
{warn ? (
<div>
<h1>WARNING MESSAGE...</h1>
<button onClick={handleContinue}>Confirm</button>
</div>
) : (
""
)}
<label htmlFor="test-input">
<input
id="test-input"
ref={inputRef}
type="file"
onChange={handleChange}
onClick={handleClick}
/>
</label>
</div>
);
}
最佳答案
单击输入时,检查单击事件是由浏览器触发还是通过脚本触发。 Event.isTrusted当浏览器触发点击事件时为真,所以在这种情况下使用 Event.preventDefault()以防止打开文件对话框。
然后编写你想做的代码,最后调用event.target.click()再次触发点击事件,但这次是 Event.isTrusted
将为 false,因此不会阻止打开文件对话框。
请记住,在打开文件对话框之前,您要执行的代码应该在 else
中。堵塞。否则,它将执行两次。
const input = document.querySelector('input');
input.addEventListener('click', (e) => {
if (e.isTrusted) {
e.preventDefault();
} else {
console.log('doing something....');
console.log('done. Opening file dialog');
}
e.target.click();
})
<input type="file"/>
关于javascript - 按住input type=file的onClick,做我想做的事,然后让浏览器启动一个文件对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62260042/