简体   繁体   中英

How do I access css/scss with react?

I have a react component where I am trying to change the background color of the css when clicking the div.

I know you can set the color in the component, but I am using this component many times, and don't to make multiple component files with just a different color, and even if I did, I am curious besides the fact.

How can I access (or even console.log to figure it out on my own) the css file and its properties through the component? Thanks ahead of time.

You can pass in the desired background color as a prop, and use internal state with an onClick handler.

Container.js

import React from 'react';
import ClickableDiv from './ClickableDiv';    

const Container = () => (
  <ClickableDiv backgroundColor="#FF0000">
    <p>This is my text.</p>
  </ClickableDiv>
);

export default Container;

ClickableDiv.js

import React, { Component } from 'react';

class ClickableDiv extends Component {
  constructor() {
    super();
    this.state = {};
    this.handleDivClick = this.handleDivClick.bind(this);
  }

  handleDivClick() {
    const { backgroundColor } = this.props;
    if (backgroundColor) this.setState({ backgroundColor });
  }

  render() {
    const { backgroundColor } = this.state;
    return (
      <div style={{ backgroundColor }} onClick={this.handleDivClick}>
        {this.props.children}
      </div>
    );
  }
}

export default ClickableDiv;

If you want to keep all background-color styles in your .css/.scss file, you will need to have a good className strategy to link the styles to your components. Here is my suggestion:

styles.scss

.blue {
  background-color: blue;

  &.clicked {
    background-color: red;
  }
}

Container.js

import React from 'react';
import ClickableDiv from './ClickableDiv.js';

const Container = () => (
  <ClickableDiv className="blue">
    <p>This is my text.</p>
  </ClickableDiv>
);

export default Container;

ClickableDiv.js

import React, { Component } from 'react';

class ClickableDiv extends Component {
  constructor() {
    super();
    this.state = { clicked: false };
    this.handleDivClick = this.handleDivClick.bind(this);
  }

  handleDivClick() {
    this.setState({ clicked: true });
  }

  render() {
    const divClassName = [this.props.classname];
    if (this.state.clicked) divClassName.push('clicked');
    return (
      <div className={divClassName.join(' ').trim()} onClick={this.handleDivClick}>
        {this.props.children}
      </div>
    );
  }
}

export default ClickableDiv;

Rendered Markup

Unclicked:

<div class="blue"><p>This is my text.</p></div>

Clicked:

<div class="blue clicked"><p>This is my text.</p></div>

最好制作一个外部CSS文件,并将您的CSS代码写入该文件,然后将其导入index.html中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM