我正在尝试了解和使用带有React和Redux的HOC。我有以下设置。我将有多个使用临时按钮并传递自己的onClick的按钮。并想知道:
a。这是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);
答案 0 :(得分:0)
发生这种情况是因为您使用
const composeFooterButton = compose(
connect(mapStateToProps),
FooterButtonWrapper
);
export default composeFooterButton;
用于HOC功能而不是组件。
compose
和connect
都可以包装您的组件。
因此,您的HOC可能是:
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';
export default function FooterButtonWrapper(FooterButtonWrapped, onClick) {
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) => ({});
return connect(mapStateToProps)(FooterButton);
}