withFocusReturn 是一个高阶组件,通常用于短生命周期元素(如模态框、下拉菜单)的场景。当该元素卸载时,焦点应恢复到触发其渲染的先前聚焦元素。
用法
withFocusReturn
import { useState } from 'react';
import { withFocusReturn, TextControl, Button } from '@wordpress/components';
const EnhancedComponent = withFocusReturn( () => (
<div>
Focus will return to the previous input when this component is unmounted
<TextControl
autoFocus={ true }
onChange={ () => {} }
/>
</div>
) );
const MyComponentWithFocusReturn = () => {
const [ text, setText ] = useState( '' );
const unmount = () => {
document.activeElement.blur();
setText( '' );
};
return (
<div>
<TextControl
placeholder="Type something"
value={ text }
onChange={ ( value ) => setText( value ) }
/>
{ text && <EnhancedComponent /> }
{ text && (
<Button variant="secondary" onClick={ unmount }>
Unmount
</Button>
) }
</div>
);
};
withFocusReturn 可以选择性地作为高阶函数创建器调用。传入一个选项对象后,将返回一个新的高阶函数。
目前支持以下选项:
onFocusReturn
一个可选函数,允许开发者自定义焦点返回行为。如果希望跳过默认的焦点返回行为,应从该函数返回 false。
- 类型:
Function - 是否必需:否
示例:
function MyComponent() {
return <textarea />;
}
const EnhancedMyComponent = withFocusReturn( {
onFocusReturn() {
document.getElementById( 'other-input' ).focus();
return false;
},
} )( MyComponent );