搜尋

首頁  >  問答  >  主體

如何在React中基於父標籤新增子標籤的css?

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 是父標籤,我在同一標籤中套用了樣式,我希望它也適用於子標籤 ()。

P粉258788831P粉258788831524 天前612

全部回覆(1)我來回復

  • P粉826283529

    P粉8262835292023-09-14 12:15:28

    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;

    回覆
    0
  • 取消回覆