:door: React 组件和钩子,可监听 beforeunload 窗口事件。
Listen to the beforeunload window event in React.
useBeforeunload Hook (recommended)useBeforeunload(handler);handler optional function to be called with BeforeUnloadEvent when beforeunload event is fired.
Passing a non-function value will disable the event listener.import { useBeforeunload } from "react-beforeunload";
const Example = (props) => {
useBeforeunload((event) => event.preventDefault());
...
};import { useBeforeunload } from "react-beforeunload";
const Example = (props) => {
const [value, setValue] = useState("");
useBeforeunload(value !== "" ? (event) => event.preventDefault() : null);
// or
useBeforeunload(value !== "" && () => true);
...
};Beforeunload ComponentonBeforeunload function to be called with BeforeUnloadEvent when beforeunload event is fired.import { Beforeunload } from "react-beforeunload";
class Example extends React.Component {
state = { value: "" };
render() {
return (
<>
{this.state.value !== "" && (
event.preventDefault()} />
)}
this.setState({ value: event.target.value })}
value={this.state.value}
/>
);
}
}:information_source: The Beforeunload component will render any children passed as-is, so it can be used as a wrapper component:
:warning: Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers.
To display a custom message in the triggered dialog box, return a string in the passed event handler function.
With useBeforeunload hook:
useBeforeunload(() => "You’ll lose your data!");With Beforeunload component:
"You’ll lose your data!"} />暂无开放 Issues,或尚未同步最近议题。