How to add css of child tag based on parent tag in React?
P粉258788831
P粉258788831 2023-09-13 18:49:57
0
1
540

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;

Note: can be dynamic. H2 is the parent tag and I have applied the style in the same tag and I want it to apply to the child tags as well ().

P粉258788831
P粉258788831

reply all(1)
P粉826283529

JSX style attributes are similar to HTML style attributes. Both the style attribute and attribute only accept CSS properties. Therefore, the use of selectors, pseudo-elements or pseudo-classes is not allowed.

Using style attributes

Replace the following:

const style = {
    h2 : {
        fontSize: '20px';
        color: 'black';
    } & span: {
       color: 'white';
    }
}

const Main = () => {
    return (
        <h2 style={style}>Hello<span>Test</span></h2> 
   );
}

and:

const h2Style = {
  fontSize: '20px';
  color: 'black';
}
const spanStyle = {
  color: 'white';
}

const Main = () => {
    return (
        <h2 style={h2Style}>Hello<span style={spanStyle}>Test</span></h2> 
   );
}

or clearer:

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> 
   );
}

However, since you only want to define styles for h2 elements, we have more options:

CSS/SCSS

Using CSS on separate files:

import "./your-css.css";

const Main = () => {
    return (
        <h2 className="title">Hello<span>Test</span></h2> 
   );
}

Among them, the .your-css.css file contains

.title {
  fontSize: '20px';
  color: 'black';
}

.title span {
  color: 'white';
}

Even nested (if you use a preprocessor like .scss)

.title {
  fontSize: '20px';
  color: 'black';

  span {
    color: 'white';
  }
}

CSS-in-JS

Considering a more "React" solution, we could use CSS-in-JS like styled-components Learn more

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;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!