跳到主要内容
版本:7.x

useIsFocused

我们可能希望根据屏幕的当前焦点状态渲染不同的内容。该库导出了一个 useIsFocused Hook 以简化此操作

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

function ProfileScreen() {
// This hook returns `true` if the screen is focused, `false` otherwise
const isFocused = useIsFocused();

return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>{isFocused ? 'focused' : 'unfocused'}</Text>
</View>
);
}
Snack 上尝试

请注意,使用此 Hook 会在屏幕更改焦点时触发组件的重新渲染。如果您的组件很重,这可能会导致动画期间出现卡顿。您可能希望将开销大的部分提取到单独的组件中,并使用 React.memoReact.PureComponent 来最大限度地减少它们的重新渲染。

与类组件一起使用

您可以将类组件包装在函数组件中以使用 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} />;
}