Wie füge ich CSS eines untergeordneten Tags basierend auf dem übergeordneten Tag in React hinzu?
P粉258788831
P粉258788831 2023-09-13 18:49:57
0
1
493

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 ().

P粉258788831
P粉258788831

Antworte allen(1)
P粉826283529

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;
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!