在 React 和 Gatsby 中通过 className 选择 dom 元素的正确方法

Sam*_*l G 5 reactjs gatsby

刚开始反应,无法在许多简单的示例中找到快速答案。Gatsby 和 React 在运行时生成类名,因此我.page1在 scss 中的类最终是sections-module--page1--2SNjF.

选择元素并向其添加附加类的正确方法是什么?

import React from 'react';
import styles from '../scss/sections.module.scss';
import $ from 'jquery';

class Section extends React.Component {
    componentDidMount() {
       $(what??).addClass('active'); // how to select .page1 here
    }

    render() {
        return (
            <>
                <section className={styles.page1}>
                    <h2>section 1</h2>
                </section>
                <section className={styles.page2}>
                    <h2>section 2</h2>
                </section>
            </>
        )
    }
}

export default () => (
    <Section/>
)
Run Code Online (Sandbox Code Playgroud)

dys*_*unc 2

为此您不需要 jQuery,并且应该避免混合两者。

试试这个。您需要创建对该元素的引用,以便可以访问它。

import React, { Component } from 'react';
import styles from '../scss/sections.module.scss';

class Section extends Component {
  constructor(props) {
    super(props);

    this.firstSection = React.createRef();
  }

  componentDidMount() {
    this.firstSection.classList.add(`${styles.page1} ${styles.active}`);
  }

  render() {
    return (
      <div>
        <section ref={this.firstSection}>
          <h2>section 1</h2>
        </section>
        <section className={styles.page2}>
          <h2>section 2</h2>
        </section>
      </div>
    )
  }
}

export default Section;
Run Code Online (Sandbox Code Playgroud)

active类添加到模块样式 SCSS 文件的适当位置,以便您可以正确引用它。

部分.模块.scss

.page1,
.page2 {
  &.active {
     background: red; 
  }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用该classnames

import React, { Component } from 'react';
import styles from '../scss/sections.module.scss';
import classnames from 'classnames';

class Section extends Component {
  constructor(props) {
    super(props);

    this.state = {
      activeSection: 1
    };
  }

  render() {
    const classes = classnames(styles.page1, {
      [styles.active]: this.state.activeSection === 1
    });

    return (
      <div>
        <section className={classes}>
          <h2>section 1</h2>
        </section>
        <section className={styles.page2}>
          <h2>section 2</h2>
        </section>
      </div>
    )
  }
}

export default Section;
Run Code Online (Sandbox Code Playgroud)