【问题标题】:Passing in class names to react components传入类名以响应组件
【发布时间】:2015-11-20 17:30:46
【问题描述】:

我正在尝试将类名传递给 react 组件以更改其样式,但似乎无法正常工作:

class Pill extends React.Component {

  render() {

    return (
      <button className="pill {this.props.styleName}">{this.props.children}</button>
    );
  }

}

<Pill styleName="skill">Business</Pill>

我正在尝试通过传入具有相应样式的类的名称来更改药丸的样式。我是 React 的新手,所以也许我这样做的方式不对。谢谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    在 React 中,当你想传递一个解释表达式时,你必须打开一对花括号。试试:

    render () {
      return (
        <button className={`pill ${ this.props.styleName }`}>
          {this.props.children}
        </button>
      );
    }
    

    使用classnames npm 包

    import classnames from 'classnames';
    
    render() {
      return (
        <button className={classnames('pill', this.props.styleName)}>
          {this.props.children}
        </button>
      );
    }
    

    【讨论】:

    • 为什么更好:性能?可读性?其他的 ?文字字符串(你的第一个例子)是 ES6 的一部分,所以它是一个标准。它减少了代码并避免了导入。它感觉对我来说更好,但其他解决方案可能有争议。
    • 在上面的例子中你是绝对正确的,最好使用 ES6 字符串。当您必须处理条件时,我会说类名在可读性和 DRY 方面更好,例如在类名自述文件中显示 github.com/JedWatson/classnames#usage-with-reactjs。
    • {} 大括号、[] 括号、() 括号 - 您无需说“花括号”,因为根据定义,大括号是花括号。
    • 需要注意的重要一点:如果props.styleName 是可选的并且您将其省略,那么您的class 列表中将包含undefined。所以{`pill ${ this.props.styleName }`} 不是很好。最后你也会有多余的空格。
    【解决方案2】:

    仅供参考,对于无状态组件:

    // ParentComponent.js
    import React from 'react';
    import { ChildComponent } from '../child/ChildComponent';
    
    export const ParentComponent = () =>
      <div className="parent-component">
        <ChildComponent className="parent-component__child">
          ...
        </ChildComponent>
      </div>
    
    // ChildComponent.js
    import React from 'react';
    
    export const ChildComponent = ({ className, children }) =>
      <div className={`some-css-className ${className}`}>
        {children}
      </div>
    

    将呈现:

    <div class="parent-component">
      <div class="some-css-className parent-component__child">
        ...
      </div>
    </div>
    

    【讨论】:

    • 不应该将 className 属性添加到 React 组件,将 className 传递给第一个容器元素,而不是将其作为名称属性传递?
    • @theSereneRebel 不,它没有。在此处查看示例:codesandbox.io/s/clever-knuth-enyju
    • @theSereneRebel 这是否是一件好事是另一个话题。
    【解决方案3】:

    pill ${this.props.styleName} 在不设置 props 时会得到“pill undefined”

    我更喜欢

    className={ "pill " + ( this.props.styleName || "") }
    

    或

    className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }
    

    【讨论】:

    • 最后你仍然会有一个多余的空格。并不是说它改变了什么,而是仍然。
    • 我像这样停止了空白区域: className={props.styleName ? "药丸" + props.styleName : "药丸" }
    【解决方案4】:

    对于任何感兴趣的人,我在使用 css modules 和 react css modules 时遇到了同样的问题。

    大多数组件都有关联的 css 模块样式,在本例中,我的 Button 有自己的 css 文件,Promo 父组件也是如此。但我想从 Promo

    向 Button 传递一些额外的样式

    所以styleable 按钮看起来像这样:

    Button.js

    import React, { Component } from 'react'
    import CSSModules from 'react-css-modules'
    import styles from './Button.css'
    
    class Button extends Component {
    
      render() {
    
        let button = null,
            className = ''
    
        if(this.props.className !== undefined){
            className = this.props.className
        }
    
        button = (
          <button className={className} styleName='button'>
            {this.props.children}
          </button>
        )
    
        return (
            button
        );
      }
    };
    
    export default CSSModules(Button, styles, {allowMultiple: true} )
    

    在上面的 Button 组件中,Button.css 样式处理常见的按钮样式。在这个例子中只是一个.button 类

    然后在我想要使用Button的组件中,并且我还想修改按钮的位置之类的东西,我可以在Promo.css中设置额外的样式并作为className 道具。在此示例中再次调用.button 类。我可以称它为任何东西,例如promoButton.

    当然,对于 css 模块,该类将是 .Promo__button___2MVMD,而按钮类将类似于 .Button__button___3972N

    Promo.js

    import React, { Component } from 'react';
    import CSSModules from 'react-css-modules';
    import styles from './Promo.css';
    
    import Button from './Button/Button'
    
    class Promo extends Component {
    
      render() {
    
        return (
            <div styleName='promo' >
              <h1>Testing the button</h1>
              <Button className={styles.button} >
                <span>Hello button</span>
              </Button>
            </div>
          </Block>
        );
      }
    };
    
    export default CSSModules(Promo, styles, {allowMultiple: true} );
    

    【讨论】:

    • 2018 年更新:使用 propTypes 和 defaultProps 处理属性可能存在或可能不存在的情况更简洁,更可取。
    【解决方案5】:

    正如其他人所说,使用带有花括号的解释表达式。

    但不要忘记设置默认值。
    其他人建议使用 OR 语句来设置空字符串 if undefined。

    但最好声明你的 Props。

    完整示例:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types';
    
    class Pill extends Component {
    
      render() {
    
        return (
          <button className={`pill ${ this.props.className }`}>{this.props.children}</button>
        );
      }
    
    }
    
    Pill.propTypes = {
      className: PropTypes.string,
    };
    
    Pill.defaultProps = {
      className: '',
    };
    

    【讨论】:

      【解决方案6】:

      您可以通过使用this.props.className“插入”从父组件传递到子组件的类名来实现这一点。示例如下:

      export default class ParentComponent extends React.Component {
        render(){
          return <ChildComponent className="your-modifier-class" />
        }
      }
      
      export default class ChildComponent extends React.Component {
        render(){
          return <div className={"original-class " + this.props.className}></div>
        }
      }
      

      【讨论】:

        【解决方案7】:

        在 Typescript 中,您需要设置 HTMLAttributes 和 React.FunctionComponent 的类型。

        在大多数情况下,您需要将其扩展到另一个接口或类型。

        const List: React.FunctionComponent<ListProps &
          React.HTMLAttributes<HTMLDivElement>> = (
          props: ListProps & React.HTMLAttributes<HTMLDivElement>
        ) => {
          return (
            <div className={props.className}>
              <img className="mr-3" src={props.icon} alt="" />
              {props.context}
            </div>
          );
        };
        
        interface ListProps {
          context: string;
          icon: string;
        }
        

        【讨论】:

          【解决方案8】:

          使用 React 16.6.3 和 @Material UI 3.5.1,我在 className 中使用数组,例如 className={[classes.tableCell, classes.capitalize]}

          在你的情况下尝试以下类似的方法。

          class Pill extends React.Component {
              render() {
                  return (
                     <button className={['pill', this.props.styleName]}>{this.props.children}</button>
                  );
              }
          }
          

          【讨论】:

            【解决方案9】:

            借助 React 对字符串插值的支持,您可以执行以下操作:

            class Pill extends React.Component {
                render() {
                   return (
                      <button className={`pill ${this.props.styleName}`}>{this.props.children}</button>
                   );
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-08-04
              • 2021-02-06
              • 2019-02-27
              • 2017-07-20
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多