简体   繁体   English

如果变量== React中的某些内容,如何将类分配给元素?

[英]How to assign a class to an element if variable == something in React?

I am new to React, worked with Angular a lot before. 我是React的新手,之前和Angular合作过很多次。 In Angular it's as simple as possible to assign some class depending on variables like this: 在Angular中,尽可能简单地根据变量分配一些类,如下所示:

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

How can I do a similar thing inside a template with React? 如何使用React在模板中执行类似的操作?

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

Longer answer: 更长的回答:

It's not much different in React, besides you write a plain old JavaScript, so lots of control here. 它在React中并没有太大的不同,除了你写一个简单的旧JavaScript,所以在这里有很多控制权。 Also, React already has a nifty addon to make it even easier. 此外,React已经有一个漂亮的插件,使它更容易。 In this case your component 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.com/lekinokecoge/1/edit?html,css,js,output 以下是工作示例: http//jsbin.com/lekinokecoge/1/edit?html,css,js,output

Just try to change the value here: 只是尝试在这里更改值:

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

An alternative to classSet is often using a simple object lookup. classSet的替代方法通常是使用简单的对象查找。

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

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

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