【发布时间】:2018-08-22 10:20:05
【问题描述】:
我正在尝试制作一个 HOC,为 React js 中图标组件中的参数“color”分配值。 我有 3 种不同的颜色。它们如下: pimary 是 #f7a014 次要是#dd8b08 三元是#56t00
所以我可以这样做:
<MyComponent color='primary' />
这是我的 withColor HOC:
import React from 'react';
import propTypes from 'prop-types';
function mapColors(color) {
if (color === 'primary') {
return '#f8af39';
}
if (color === 'secondary') {
return '#fff';
}
if (color === 'ternary') {
return '#004c64';
}}
export const withColor = WrappedComponent => {
const NewComponent = ({ color, ...props }) => (
<WrappedComponent color={mapColors(color)} {...props} />
);
NewComponent.propTypes = {
color: propTypes.oneOf(['primary', 'secondary', 'ternary']),
};
return NewComponent;
};
export default withColor;
这是我的组件,里面有图标:
import React from 'react';
import { RequestCloseModal } from 'HOC/connectModals';
import { compose } from 'redux';
import {
Collapse,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
} from 'reactstrap';
import { ChevronDown, ChevronUp } from 'react-feather';
import PropTypes from 'prop-types';
import Industrie from 'components/Icons/Industrie';
import FinancerContainer from 'backoffice/containers/Financer/FinancerContainer';
import withContainer from 'HOC/withContainer';
import withColor from 'HOC/WithColor';
class FinancerMatchingDetails extends RequestCloseModal {
static propTypes = {
isOpen: PropTypes.bool,
};
constructor(props) {
super(props);
this.state = {
collapse: false,
};
}
toggle = () => {
this.setState({ collapse: !this.state.collapse });
};
render() {
const { isOpen } = this.props;
return (
<Modal size="xxl" isOpen={isOpen} toggle={this.close}>
<ModalHeader toggle={this.close}>
<div className="col-md-3">
<h4>Some text</h4>
<p>Some text</p>
</div>
</div>
</div>
<div>
<h4>Some text</h4>
{this.state.collapse ? (
<ChevronUp height={20} onClick={this.toggle} />
) : (
<ChevronDown height={20} onClick={this.toggle} />
)}
</div>
</ModalBody>
<ModalFooter>
<div className="container">
<Collapse isOpen={this.state.collapse}>
<div className="row">
<div className="col">
<MyIcon color="primary" />
</div>
</Collapse>
</div>
</ModalFooter>
</Modal>
);
}
}
export default compose(withContainer(FinancerContainer), withColor)(
FinancerMatchingDetails,
);
我是 HOC 新手,无法分配原色。感谢您的帮助。
【问题讨论】:
-
你到底为什么要这样做
-
你为什么不只是传递道具
标签: javascript reactjs function parameters higher-order-components