简体   繁体   English

ReactJS:如何将className添加到子组件

[英]ReactJS: How to add a className to a child component

I'm trying to add a class name to a child component, preserving the original classes that may be set to the component. 我试图将一个类名称添加到子组件,以保留可能设置为该组件的原始类。

Here is the code: 这是代码:

import React, { Component } from "react";
import PropTypes from "prop-types";

    class ClassExtender extends Component {
        getChildrenWithProps = () => {
            let addedClass = "my-new-css-class-name";

            return React.Children.map(this.props.children, child => 
                React.cloneElement(child, { className: [child.className, addedClass] })
            );
        };

        render = () => {
            return this.getChildrenWithProps();
        };
    }

    export default ClassExtender;

I'm getting a wrong result when my component renders: 当我的组件渲染时,我得到一个错误的结果:

<div class=",my-new-css-class-name">Test</div>

That points to two possible problems: 这指出了两个可能的问题:

  1. The comma may indicate I need to change code to React.cloneElement(child, { className: child.className + " " + addedClass }); 逗号可能表示我需要将代码更改为React.cloneElement(child, { className: child.className + " " + addedClass }); . That is a easy step. 这是一个简单的步骤。
  2. child.className is returning null . child.className返回null How can I retrieve the current classe(s) attached to the child component ? 如何获取子组件上附加的当前类?

child.className is returning null. child.className返回null。 How can I retrieve the current classe(s) attached to the child component ? 如何获取子组件上附加的当前类?

child.props.className

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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