gpt4 book ai didi

javascript - 如何使用 HOC 为 React 中的组件赋值?

转载 作者:行者123 更新时间:2023-12-03 01:16:59 28 4
gpt4 key购买 nike

我正在尝试创建一个 HOC,为 React js 中的图标组件中的参数“颜色”赋值。我有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 新手,无法指定主色。感谢您的帮助。

最佳答案

您定义了 HOC,但从未通过它传递任何组件。例如

import withColor from 'HOC/WithColor'; // your HOC
import SomeComponent from 'SomeComponent'; // component that you would like to use with HOC

然后您需要定义一个组件,该组件是 HOC 应用于您的组件的结果:

const ColoredComponent = withColor(SomeComponent);

然后你就可以按照你的预期使用它了:

<ColoredComponent color="primary" />

关于javascript - 如何使用 HOC 为 React 中的组件赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964714/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com