在React和Gatsby中选择DOM元素的正确方法是通过类名。

5

如果您刚接触React,可能很难在许多简单的示例中找到快速答案。 Gatsby和React会在运行时生成类名,因此我的scss文件中的类.page1最终会变成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/>
)

好笑 ;)在React中,您可以以多种方式完成它:https://dev59.com/CF0a5IYBdhLWcg3wRGzp https://stackoverflow.com/questions/51809623/react-switching-between-lists-with-same-class/51810348#51810348 - xadm
这些帖子没有涵盖使用CSS模块进行条件类赋值的情况,这需要以不同的方式处理。原则是相同的,但引用是不同的,这是令人困惑的部分。@Chev,这些答案有帮助吗? - dysfunc
1个回答

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;

在正确的位置将active类添加到您的模块样式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;

看看上面的第一个例子,对于活动样式的引用是不正确的。.active 样式不在 scss 的根目录下,而是嵌套在父级 .page 中,所以这实际上是行不通的,除非 .active 没有被嵌套。 - Samuel Goldenbaum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接