首页 > 解决方案 > 如何将类应用于不支持 className 的外部组件?

问题描述

在我的 React 项目中,我使用了一个组件库:

<customcomponent />

但是,该库组件不支持传递 className。因此我不能使用这种方法将样式应用于组件,如下所示:

<customcomponent className='mystyles' />

在这种情况下如何将样式应用于组件?

标签: reactjs

解决方案


您必须创建一个包装器组件,该组件用一个接受className.

const DoesntSupportClassNameWrapper = (props) => {
  const { className, style, ...rest } = props;
  return (
    <div className={className} style={style}>
      <DoesntSupportClassName {...rest} />
    </div>
  );
};

完整示例

Edit @ CodeSandbox

应用程序.jsx

import React from "react";
import PropTypes from "prop-types";
import { DoesntSupportClassName, SupportsClassName } from "./components";
import "./styles.css";

const styles = {
  heading: {
    color: "red"
  }
};

const DoesntSupportClassNameWrapper = (props) => {
  const { className, style, ...rest } = props;
  return (
    <div className={className} style={style}>
      <DoesntSupportClassName {...rest} />
    </div>
  );
};

DoesntSupportClassNameWrapper.propTypes = {
  className: PropTypes.string,
  style: PropTypes.object
};

const App = () => {
  return (
    <div className="App">
      <SupportsClassName text="Heading 1" className="heading" />
      <DoesntSupportClassName
        text="Heading 2"
        className="heading"
        style={styles.heading}
      />
      <DoesntSupportClassNameWrapper text="Heading 3" className="heading" />
      <DoesntSupportClassNameWrapper text="Heading 4" style={styles.heading} />
    </div>
  );
};

export default App;

不支持类名.jsx

import React from "react";
import PropTypes from "prop-types";

const DoesntSupportClassName = (props) => {
  const { text } = props;
  return <h1>{text}</h1>;
};

DoesntSupportClassName.propTypes = {
  text: PropTypes.string
};

export default DoesntSupportClassName;

SupportsClassName.jsx

import React from "react";
import PropTypes from "prop-types";

const SupportsClassName = (props) => {
  const { text, className } = props;
  return <h1 className={className}>{text}</h1>;
};

SupportsClassName.propTypes = {
  className: PropTypes.string,
  text: PropTypes.string
};

export default SupportsClassName;

推荐阅读