【问题标题】:How to apply class to an external component that does not support className?如何将类应用于不支持 className 的外部组件?
【发布时间】:2021-02-25 22:30:43
【问题描述】:

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

<customcomponent />

但是,库组件不支持传递 className。因此我不能使用这种方法将样式应用到这样的组件:

<customcomponent className='mystyles' />

这种情况下如何给组件应用样式?

【问题讨论】:

  • 这里有什么库问题?如果 API 不包含此内容,您可以通过类对其进行样式设置,但这可能有点 hacky,这意味着该组件不打算设置样式。在这种情况下,您可以尝试在该 github 上发布问题以添加该功能。但在很多情况下,组件会封装类并在运行时添加唯一的哈希
  • 一个很好的例子是 Material-UI,您可以在其中为预定义的组件类分配您的类,例如root。但是您可以在此处分享您尝试设置样式的库以进行更多说明
  • 您需要在此处包含一个示例。

标签: reactjs


【解决方案1】:

您必须创建一个包装器组件,用一个接受className 的 div 来包装您的组件。

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

完整示例

Edit @ CodeSandbox

App.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;

DoesntSupportClassName.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;

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2014-01-19
    • 2017-10-19
    • 2013-03-27
    • 1970-01-01
    相关资源
    最近更新 更多