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;
注意:可以是动态的。 H2 是父标签,我在同一标签中应用了样式,我希望它也适用于子标签 ()。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
JSX 样式属性与 HTML 的样式属性类似。 style 属性和 attribute 都只接受 CSS 属性。因此,不允许使用选择器、伪元素或伪类。
使用样式属性
替换以下内容:
const style = { h2 : { fontSize: '20px'; color: 'black'; } & span: { color: 'white'; } } const Main = () => { return ( <h2 style={style}>Hello<span>Test</span></h2> ); }与:
const h2Style = { fontSize: '20px'; color: 'black'; } const spanStyle = { color: 'white'; } const Main = () => { return ( <h2 style={h2Style}>Hello<span style={spanStyle}>Test</span></h2> ); }或者更清晰的:
const styles = { h2: { fontSize: '20px'; color: 'black'; }, span: { color: 'white'; } } const Main = () => { return ( <h2 style={styles.h2}>Hello<span style={styles.span}>Test</span></h2> ); }但是,由于您只想定义 h2 元素的样式,因此我们有更多选项:
CSS/SCSS
在单独的文件上使用 CSS:
import "./your-css.css"; const Main = () => { return ( <h2 className="title">Hello<span>Test</span></h2> ); }其中,
.your-css.css文件包含.title { fontSize: '20px'; color: 'black'; } .title span { color: 'white'; }甚至是嵌套(如果您使用 .scss 等预处理器)
.title { fontSize: '20px'; color: 'black'; span { color: 'white'; } }CSS-in-JS
考虑一个更“React”的解决方案,我们可以使用 CSS-in-JS,例如
styled-components了解更多import React from 'react'; import styled from 'styled-components'; const Title = styled.h2` fontSize: '20px'; color: 'black'; span { color: 'white'; } `; const Main = () => { return ( <Title>Hello<span>Test</span></Title> ); } export default Main;