An open API service indexing awesome lists of open source software.

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事件

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