import React from 'react'; const style = { h2 : { fontSize: '20px'; color: 'black'; } & span: { color: 'white'; } } const Main = () => { return ( <h2 style={style}>Hello<span>Test</span></h2> ); } export default Main;
Hinweis: kann dynamisch sein. H2 ist das übergeordnete Tag und ich habe den Stil im selben Tag angewendet und möchte, dass er auch auf die untergeordneten Tags angewendet wird ().
JSX 样式属性与 HTML 的样式属性类似。 style 属性和 attribute 都只接受 CSS 属性。因此,不允许使用选择器、伪元素或伪类。
使用样式属性
替换以下内容:
与:
或者更清晰的:
但是,由于您只想定义 h2 元素的样式,因此我们有更多选项:
CSS/SCSS
在单独的文件上使用 CSS:
其中,
.your-css.css
文件包含甚至是嵌套(如果您使用 .scss 等预处理器)
CSS-in-JS
考虑一个更“React”的解决方案,我们可以使用 CSS-in-JS,例如
styled-components
了解更多