我正在将一个旧网站转换成React,不想改变之前编码的所有CSS文件。很多元素目前通过使用id设置其样式。有没有一种方法可以使用className={styles["#topBar"]}
正确设置样式,而无需在CSS文件夹中删除#
并替换为.
?
由于您正在使用CSS Modules,您需要稍微不同的方式访问样式。 您需要import styles from 'Component.module.css';
,然后通过引用此导入的对象styles.MyClass
声明您的样式,或者在您的情况下,因为您有连字符,您需要使用括号表示法styles["top-bar"]
这里是一个可工作的代码沙盒
//MyComponent.js
import styles from "./MyComponent.module.css";
export default function MyComponent() {
return (
<div id={styles["top-bar"]}>
<h2>My Component</h2>
<InnerComponent id="inner" />
</div>
);
}
function InnerComponent({ id }) {
return (
<div id={styles[id]}>
<h3>Inner Component</h3>
<p id={styles.para}>Styled Paragraph</p>
</div>
);
}
//MyComponent.module.css
#top-bar {
width: 90vw;
margin: 1rem auto;
padding: 1rem;
text-align: center;
background-color: LightPink;
}
#inner {
background-color: LightBlue;
text-align: left;
}
#para {
color: red;
}
以下是一个快速示例,展示如何使用ID使其工作。
function MyComponent() {
return (
<div id="top-bar">
<h2>My Component</h2>
<InnerComponent id="inner" />
</div>
)
}
function InnerComponent({id}) {
return (
<div id={id}>
<h3>Inner Component</h3>
</div>
)
}
ReactDOM.render(<MyComponent />, document.getElementById('App'));
#top-bar {
width: 90vw;
margin: 1rem auto;
padding: 1rem;
text-align:center;
background-color: LightPink;
}
#inner {
background-color: LightBlue;
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="App"></div>
#top-bar {...}
在该文件中,并且你已经在HeaderToolbar.js中应用了它,它就应该生效。 - pilchard
return (<div id="myID">)
或者从 props 传递<MyComponent id="compId" />
...MyComponent = ({id}) => {... return (<div id={id}>)}
。文档:所有支持的 HTML 属性。 - pilchard