23

我正在尝试在 React 中创建一个无状态组件,其唯一目的是充当可重用的包装器。我也在使用 CSS 模块,因为我想要完全模块化的 CSS。

问题是我不想添加不必要<div>的元素(甚至更多),而是我想使用 React 的片段。

现在,我遇到的问题是片段(至少现在)不接受类名。所以如果我试试这个:

// 在 Wrapper.js 中:

import React, { Fragment } from 'react'
import styles from './Wrapper.css'

const wrapper = (props) => (
    <Fragment className={styles.wrapper}>
        {props.children}
    </Fragment>
)

export default wrapper

在(例如)Navbar.js 中:

import React from 'react'
import styles from './Navbar.css'
import Wrapper from '../../Layout/Wrapper'

const navBar = (props) => (
    <nav className={styles.navBar}>
        <Wrapper>
            This is the site's main navigation bar.
        </Wrapper>
    </nav>
)

export default navBar

现在我当然可以使用 div 而不是 Fragment,但是有没有其他解决方法可以避免使用不必要的标记,我在晚上的这个时间完全不知道这些?:)

提前感谢您提供任何见解、建议、更正或任何其他形式的帮助!

4

4 回答 4

43

Fragments let you group a list of children without adding extra nodes to the DOM. - https://reactjs.org/docs/fragments.html

What Fragments tries to solve its the unnecessary dom elements but this doesn't mean that Fragments will replace div entirely. If you need to add a className there, its clearl that either you add a dom element in this case another div or add the class to its parent.

于 2018-03-02T13:29:19.517 回答
8

使用Fragment意味着不向 DOM 添加额外的节点。

如果要将 a 分配className给节点,则必须使用div.

于 2018-03-02T13:45:43.667 回答
2
  1. 创建一个 css 文件并将其导入到您的 App.js 中
  2. 使用Class.js 创建一个高阶组件,如下所示

    import React from  'react';
    
    const withClass = (WrappedComponent, className) => {
        return props => (
            <div className={className}>
                <WrappedComponent {...props} />
            </div>
        );
    };
    
    export default withClass;

  1. 也导入您的 hoc。
  2. 在您的 App.js 中编写如下内容

    <React.Fragment>
        <p>Some JSX code here</p>
    <React.Fragment>
    
    export default withClass(App, classes.App);

我在我的 css 文件中创建了 .App 类并将其导入,以便我以后可以使用它classes.App。这样,您可以应用您在 css 中创建的任何 css 类。您可以使用相同的 wrapperComponent 来包装您拥有的每个组件,只需导入它并更改组件中的导出即可。您只需选择您选择的类名并在组件的导出语句中使用它。当您使用扩展运算符(...)编写道具时。组件中的所有道具都将传递给这个 wrapperComponent。

PS:英语不是我的母语,所以我不擅长解释,但这段代码可以解决问题。感谢版主查看我的解释。

于 2019-12-24T13:16:21.803 回答
0

所以Wrapper/Fragment所做的唯一一件事就是充当nav?的子级的 CSS 包装器。

我对 css-modules 不是很有经验,但是如果我想避免只为 className 使用额外的 DOM 节点,我会使用类似这样的东西来将两个 classNames 应用于<nav>

import React from 'react'
import navStyles from './Navbar.css'
import wrapperStyles from './Wrapper.css'

const navBar = (props) => (
    <nav className={`${navStyles.navBar} ${wrapperStyles.wrapper}`}>
       This is the site's main navigation bar.
    </nav>
)

export default navBar
于 2018-03-02T13:55:01.170 回答