无法在DOM中渲染时向按钮组件添加类名

时间:2018-10-17 16:39:14

标签: reactjs jsx

能否请您查看此摘要,并让我知道为什么我无法使用

传递.btn-primary的类名
<Button styleClass="btn-primary" text='Primary Button' />

运行此命令后,我在检查器的元素中看到${styleClass}而不是类名

enter image description here

const Button = ({ styleClass, text }) => {
  return (
    <button
      type="button"
      className={'btn ${styleClass}'}
    >
      {text}
    </button>
  );
};
ReactDOM.render(
               <div>
                 <Button styleClass="btn-primary" text='Primary Button' />
               </div>
, window.root);
body{
padding:30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div id="root"></div>

1 个答案:

答案 0 :(得分:2)

使用<ion-item [class.ng-invalid]="!thisForm.controls.smallerValue.valid" [class.ng-valid]="thisForm.controls.smallerValue.valid"> grave accent字符串的'字符改为反勾号((template literals)字符:

${}
const Button = ({ styleClass, text }) => {
  return (
    <button
      type="button"
      className={`btn ${styleClass}`}
    >
      {text}
    </button>
  );
};
ReactDOM.render(
  <div>
    <Button styleClass="btn-primary" text='Primary Button' />
  </div>
, window.root);
body{
  padding: 30px;
}

或不使用字符串插补:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div id="root"></div>

希望有帮助!