首页 > 解决方案 > React 不应用 CSS 规则

问题描述

我正在使用 React 创建一些按钮和 CSS 来设置主题样式。所以我创建了一个类按钮:

export default class Button extends React.Component{
  public className: string;

    constructor(props){
      super(props);
      this.className = props.className ? props.className : "";
    }

    public render() {
      return (
        <button className = {this.className}>
          {this.value}
        </button>
      );
    }
  }

这是我的 CSS:

.my-css {
    width: 300px;
    height: 200px;
    border-radius: 8px;
}

这就是我使用它的方式:

<Button className = "my-css" value = "Test" />

为什么在检查器中我没有看到我的规则已加载?

谢谢谁来回答我!:-)

标签: cssreactjsjsx

解决方案


render你应该直接在你的函数中引用你的道具:

export default class Button extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <button className={this.props.className}> 
        {this.props.value}
      </button>
    );
  }
}

推荐阅读