简体   繁体   English

传入类名以响应组件

[英]Passing in class names to react components

I am trying to pass in a classname to a react component to change it's style and cannot seem to get working:我正在尝试将类名传递给反应组件以更改其样式并且似乎无法正常工作:

class Pill extends React.Component {

  render() {

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

}

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

I am trying to change the style of the pill by passing in the name of the class that has the respective style.我正在尝试通过传入具有相应样式的类的名称来更改药丸的样式。 I am new to React so maybe I am not doing this the right way.我是 React 的新手,所以也许我这样做的方式不对。 Thanks谢谢

In React, when you want to pass an interpreted expression, you have to open a pair of curly braces.在 React 中,当你想传递一个解释表达式时,你必须打开一对花括号。 Try:尝试:

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

Using the classnames npm package使用名 npm 包

import classnames from 'classnames';

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

Just for the reference, for stateless components:仅供参考,对于无状态组件:

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

Will render:将渲染:

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

pill ${this.props.styleName} will get "pill undefined" when you don't set the props当您不设置道具时, pill ${this.props.styleName}将获得“药丸未定义”

I prefer我更喜欢

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

or或者

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

For anyone interested, I ran into this same issue when using css modules and react css modules .对于任何感兴趣的人,我在使用css modulesreact css modules时遇到了同样的问题。

Most components have an associated css module style, and in this example my Button has its own css file, as does the Promo parent component.大多数组件都有关联的 css 模块样式,在这个例子中,我的Button有自己的 css 文件, Promo父组件也是如此。 But I want to pass some additional styles to Button from Promo但我想从PromoButton传递一些额外的样式

So the style able Button looks like this:所以style able Button 看起来像这样:

Button.js按钮.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} )

In the above Button component the Button.css styles handle the common button styles.在上面的 Button 组件中, Button.css样式处理常见的按钮样式。 In this example just a .button class在这个例子中只是一个.button

Then in my component where I want to use the Button , and I also want to modify things like the position of the button, I can set extra styles in Promo.css and pass through as the className prop.然后在我想要使用Button的组件中,并且我还想修改按钮的位置等内容,我可以在Promo.css中设置额外的样式并作为className属性传递。 In this example again called .button class.在这个例子中再次调用了.button类。 I could have called it anything eg promoButton .我可以称它为任何东西,例如promoButton

Of course with css modules this class will be .Promo__button___2MVMD whereas the button one will be something like .Button__button___3972N当然,对于 css 模块,此类将是.Promo__button___2MVMD而按钮类将类似于.Button__button___3972N

Promo.js 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} );

As other have stated, use an interpreted expression with curly braces.正如其他人所说,使用带有花括号的解释表达式。

But do not forget to set a default.但不要忘记设置默认值。
Others has suggested using a OR statement to set a empty string if undefined .其他人建议使用 OR 语句来设置空字符串 if undefined

But it would be even better to declare your Props.但是声明你的 Props 会更好。

Full example:完整示例:

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: '',
};

In Typescript you need to set types of HTMLAttributes and React.FunctionComponent .在 Typescript 中,您需要设置HTMLAttributesReact.FunctionComponent的类型。

In most cases you will need will be extending it to another interface or type.在大多数情况下,您需要将其扩展到另一个接口或类型。

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

interface ListProps {
  context: string;
  icon: string;
}

You can achieve this by "interpolating" the className passed from the parent component to the child component using this.props.className .您可以通过使用this.props.className “插值”从父组件传递到子组件的 className 来实现这一点。 Example below:下面的例子:

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>
  }
}

With React 16.6.3 and @Material UI 3.5.1, I am using arrays in className like className={[classes.tableCell, classes.capitalize]}使用 React 16.6.3 和 @Material UI 3.5.1,我在 className 中使用数组,例如className={[classes.tableCell, classes.capitalize]}

Try something like the following in your case.在您的情况下尝试以下操作。

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

With React's support for string interpolation, you could do the following:借助 React 对字符串插值的支持,您可以执行以下操作:

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

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

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