https://github.com/sbdavid/react-navigation-lazy-screen
实现页面懒加载,并补发react-navigation的首次focus事件
https://github.com/sbdavid/react-navigation-lazy-screen
Last synced: 29 days ago
JSON representation
实现页面懒加载,并补发react-navigation的首次focus事件
- Host: GitHub
- URL: https://github.com/sbdavid/react-navigation-lazy-screen
- Owner: SBDavid
- License: mit
- Created: 2021-08-06T02:31:09.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2021-11-11T05:58:28.000Z (over 3 years ago)
- Last Synced: 2024-10-14T14:18:44.749Z (8 months ago)
- Language: TypeScript
- Size: 404 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# react-navigation-lazy-screen
实现页面懒加载,并补发首次focus事件
此库需要结合react-navigation使用,目前支持 StackNavigaton 和 BottomNavigation。
词库解决的主要问题为:当我们在 react-navigation 中使用懒加载来加载页面时无法收到首个 focus 事件。react-navigation-lazy-screen 会向页面补发首个 focus 事件。并且 react-navigation-lazy-screen 在使用形式上更加简洁。
## Installation
```sh
npm install react-navigation-lazy-screen
```## Usage
### 1. 在Router中加入 LazyScreen 组件
```js
import LazyScreen from "react-navigation-lazy-screen";// Tab路由
const Tab = createBottomTabNavigator();
function Tabs() {
return (
{(props) => {
return (
Loading...} // 如果懒加载失败则显示 fallback
factory={() => import('../screen/TabScreen')} // 通过懒加载方式加载组件
/>
);
}}
{/* ... */}
);
}
// Stack 路由{(props) => {
return (
Loading...}
factory={() => import('../screen/StackScreen')}
/>
);
}}```
### 2. 在页面中绑定 focus 和 blur 事件
```js
export default class StackScreen extends React.Component {
unsubscribeFocus: any;
unsubscribeBlur: any;componentDidMount() {
// 绑定事件
this.unsubscribeFocus = this.props.addFocusListener(() => {
console.info(' focus');
});this.unsubscribeBlur = this.props.addBlurListener(() => {
console.info(' blur');
});
}componentWillUnmount() {
// 解绑事件
this.unsubscribeFocus();
this.unsubscribeBlur();
}render() {
return (
);
}
}```
### 3. 在组件中监听路由事件
> 您可以通过react context机制在页面的任何子组件中监听 focus blur 事件```js
import { AddListenerContext } from 'react-navigation-lazy-screen';class InnerComp extends React.PureComponent<{ pageName: string }> {
unsubscribeFocus: any;static contextType = AddListenerContext;
componentDidMount() {
this.unsubscribeFocus = this.context.addListener('focus', () => {
console.info(this.props.pageName + ' InnerComp focus');
});// same for blur
}componentWillUnmount() {
this.unsubscribeFocus();
}render() {
return {'The ' + this.props.pageName + ' InnerComp'};
}
}
```
## Example请参考 example 文件夹
## License
MIT