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

Correct way to select dom element by className in React and Gatsby

反应新手,无法在众多简单示例中快速找到答案。 Gatsby 和 React 在 运行 时生成 class 名称,所以我在 scss 中的 class .page1 最终成为 sections-module--page1--2SNjF

select 元素并向其添加额外 class 的正确方法是什么?

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/>
)

您不需要 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;

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

sections.module.scss

.page1,
.page2 {
  &.active {
     background: red; 
  }
}

您还可以使用 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;