reactjs - 如何将类应用于不支持 className 的外部组件?
问题描述
在我的 React 项目中,我使用了一个组件库:
<customcomponent />
但是,该库组件不支持传递 className。因此我不能使用这种方法将样式应用于组件,如下所示:
<customcomponent className='mystyles' />
在这种情况下如何将样式应用于组件?
解决方案
您必须创建一个包装器组件,该组件用一个接受className
.
const DoesntSupportClassNameWrapper = (props) => {
const { className, style, ...rest } = props;
return (
<div className={className} style={style}>
<DoesntSupportClassName {...rest} />
</div>
);
};
完整示例
应用程序.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;
推荐阅读
- php - HTML 表单发送 GET 而不是 POST(XAMPP、Apache、localhost)
- c++ - 是特定于 windowsOS 的 errno STRUNATE,在 linux/mac 中寻找它的等价物。在 mbstowcs_s() 的实现中使用它
- node.js - 使用 pm2 获取节点控制台输出到文件
- c++11 - 长双无穷大
- matlab - 如何使用 MATLAB 将串行数据保存为 .txt 格式?
- c - 错误:在宏中使用时不允许使用节属性
- javascript - 为什么我更改代码时更改不影响实时
- django - 如何在 Django 应用程序中提供 Angular 图像?
- mysql - 错误代码:1054。“on 子句”中的未知列
- excel - 用标准对许多工作表求和