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:
- Static
- Dynamic
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>
);
}
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>
);
}
请注意,当屏幕更改焦点时,使用此钩子会触发组件的重新渲染。如果你的组件很重,这可能会导致动画期间出现滞后。你可能希望将昂贵的部分提取到单独的组件中,并使用 React.memo
或 React.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} />;
}