admin管理员组

文章数量:1278947

I am new to React, worked with Angular a lot before. In Angular it's as simple as possible to assign some class depending on variables like this:

<p ng-class="{warning: warningLevel==3, critical: warningLevel==5}">Mars attacks!</p>

How can I do a similar thing inside a template with React?

I am new to React, worked with Angular a lot before. In Angular it's as simple as possible to assign some class depending on variables like this:

<p ng-class="{warning: warningLevel==3, critical: warningLevel==5}">Mars attacks!</p>

How can I do a similar thing inside a template with React?

Share Improve this question edited Oct 7, 2014 at 23:16 yarden 1,9361 gold badge12 silver badges16 bronze badges asked Oct 2, 2014 at 17:03 Sergei BasharovSergei Basharov 53.9k78 gold badges207 silver badges352 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

An alternative to classSet is often using a simple object lookup.

var levelToClass = {
  "3": "warning",
  "5": "critical"
};

// ...
render: function(){
  var level = levelToClass[this.props.warningLevel] || "";
  return <p className={"message " + level}>Test</p>
}

Or in some cases a ternary:

render: function(){
  var level = this.props.warningLevel === 3 ? "warning"
            : this.props.warningLevel === 5 ? "critical"
            : "";
  return <p className={"message " + level}>Test</p>
}

Short answer: use classSet(): http://facebook.github.io/react/docs/class-name-manipulation.html

Longer answer:

It's not much different in React, besides you write a plain old JavaScript, so lots of control here. Also, React already has a nifty addon to make it even easier. In this case your ponent will look something like this:

var ClassnameExample = React.createClass({
  render: function() {
    var cx = React.addons.classSet;
    var classes = cx({
      "message": true,
      "warning": this.props.warningLevel === "3",
      "critical": this.props.warningLevel === "5"
    });
    return <p className={classes}>Test</p>;
  }
});

Here is the working example: http://jsbin./lekinokecoge/1/edit?html,css,js,output

Just try to change the value here:

React.renderComponent(<ClassnameExample warningLevel="3" />, document.body);

本文标签: javascriptHow to assign a class to an element if variablesomething in ReactStack Overflow