Skip to main content
Version: 6.x

useIsFocused

我们可能希望根据屏幕当前的焦点状态呈现不同的内容。该库导出了 useIsFocused 钩子以使这更容易:

¥We might want to render different content based on the current focus state of the screen. The library exports a useIsFocused hook to make this easier:

import { useIsFocused } from '@react-navigation/native';

// ...

function Profile() {
const isFocused = useIsFocused();

return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}

请注意,当屏幕更改焦点时,使用此钩子会触发组件的重新渲染。如果你的组件很重,这可能会导致动画期间出现滞后。你可能希望将昂贵的部分提取到单独的组件中,并使用 React.memoReact.PureComponent 来最大程度地减少它们的重新渲染。

¥Note that using this hook triggers a re-render for the component when the screen it's in changes focus. This might cause lags during the animation if your component is heavy. You might want to extract the expensive parts to separate components and use React.memo or React.PureComponent to minimize re-renders for them.

与类组件一起使用

¥Using with class component

你可以将类组件封装在函数组件中以使用钩子:

¥You can wrap your class component in a function component to use the hook:

class Profile extends React.Component {
render() {
// Get it from props
const { isFocused } = this.props;
}
}

// Wrap and export
export default function (props) {
const isFocused = useIsFocused();

return <Profile {...props} isFocused={isFocused} />;
}