創(chuàng)建
兩種方式:
代理方式的高階組件
function containerWrapper(Container, otherProps) {
// 也可以使用無狀態(tài)組件
class WrappedComponent extends Component {
componentWillMount() {
// Container的componentWillMount也會(huì)執(zhí)行
console.log('wrapper')
}
render() {
return (
<View style={{flex: 1}}>
<Container {...this.props} {...otherProps}/>
</View>
)
}
}
// 或者
// let WrappedComponent = (props) => (
// <View style={{flex: 1}}>
// <Container {...props} {...otherProps}/>
// </View>
// )
return connect(
state => ({state}),
dispatch => ({actions: bindActionCreators(actions, dispatch)})
)(WrappedComponent);
}
繼承方式的高階組件
function containerWrapper(Container) {
// 繼承Container
class WrappedComponent extends Container {
componentWillMount() {
// 需要調(diào)用super
super.componentWillMount()
console.log('wrapper')
}
render() {
return (
<View style={{flex: 1}}>
{super.render()}
</View>
)
}
}
return connect(
state => ({state}),
dispatch => ({actions: bindActionCreators(actions, dispatch)})
)(WrappedComponent);
}
調(diào)用
export default containerWrapper(TopicPage, {statusTextStyle: 'dark'})
兩種方式都可以包裝組件、擴(kuò)展生命周期方法。
不同點(diǎn)是前者實(shí)際創(chuàng)建了兩個(gè)組件,后者因?yàn)槭抢^承,所以只有一個(gè);前者可以增刪props,后者沒找到控制props的方法。
RNN通過組件的靜態(tài)屬性來設(shè)置navigator,使用代理方式的高階組件包裹后,訪問不到這些靜態(tài)屬性,需要在高階組件中加入兩行。如果是繼承方式就不需要
static navigatorStyle = Container.navigatorStyle
static navigatorButtons = Container.navigatorButtons
使用修飾器
引入修飾器(Decorator)簡化代碼,模仿connect修改高階組件
作為高階組件,都有必要轉(zhuǎn)換為修飾器實(shí)現(xiàn)
一、npm i --save-dev babel-plugin-transform-decorators-legacy
修改.babelrc
{
"presets": ["react-native"],
"plugins": ["transform-decorators-legacy"]
}
二、模仿redux connect修改container的高階組件。分解為兩層函數(shù),第一層的參數(shù)為需要的props,第二層的參數(shù)為組件
export const containerWrapper = (title) => {
return (Container)=>{
let WrappedComponent = (props)=> <Container {...props} title={title}/>
...
return WrappedComponent
}
}
三、調(diào)用
普通方式:
class TopicPage extends Component {...}
export default containerWrapper({title: '話題'})(TopicPage)
修飾器調(diào)用:
@containerWrapper({title: '話題'})
export default class TopicPage extends Component {...}