【发布时间】:2019-02-18 22:32:28
【问题描述】:
我正在尝试理解 HOC 并将其与 react 和 redux 结合使用。我有以下设置。我将有多个按钮使用 hoc 并传入他们自己的 onClick。并想知道:
一个。这是 HOC 模式的好用法吗?
b.通过在 FooterButton 的渲染函数内部进行此设置,this 引用了 DesignatedWorkerGlobalScope,而 HomeButton 内部的 iconHeigh、iconWidth 和 iconColor 变为未定义或意外值。
任何建议将不胜感激。
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { getColors, getStylesheet} from "../../styles/StyleManager";
const FooterButtonWrapper = (FooterButtonWrapped, onClick) => {
return class FooterButton extends React.Component {
constructor(props) {
super(props);
this.state = {
Theme: getStylesheet(),
colors: getColors()
}
}
_onClick = () => {
onClick(this.props.dispatch);
}
render() {
const { Theme, colors } = this.state;
return(
<TouchableOpacity onPress={this._onClick}>
<FooterButtonWrapped iconWidth={15} iconHeight={15} iconColor={"white"}/>
</TouchableOpacity>
)
}
}
}
const mapStateToProps = (state, ownProps) => ({});
const composeFooterButton = compose(
connect(mapStateToProps),
FooterButtonWrapper
);
export default composeFooterButton;
然后是一个使用它的按钮:
import React from 'react';
import { View, Text } from 'react-native';
import { push as gotoRoute } from 'react-router-redux';
import { FooterButtonWrapper } from './';
import { Home } from '../../assets';
const HomeButton = ({iconHeight, iconWidth, iconColor}) => (
<View>
<Home width={ iconWidth } height={ iconHeight } color={ iconColor }/>
<View><Text>Home</Text></View>
</View>
);
const _onClick = dispatch => {
dispatch( gotoRoute( '/' ));
}
export default FooterButtonWrapper(HomeButton, _onClick);
【问题讨论】:
标签: reactjs react-native this