Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react组件动态处理className #22

Open
youngwind opened this issue Jan 13, 2016 · 1 comment
Open

react组件动态处理className #22

youngwind opened this issue Jan 13, 2016 · 1 comment
Labels

Comments

@youngwind
Copy link
Owner

前言

在组件开发的时候我们常常会碰到类似这样的情况:满足某个特定条件的时候给某元素添加上一个类,否则不添加。之前一直用的方法是这样的:

render:function () {
  var demoClassName = "wrap";
  if (this.props.active) {
    demoClassName += " active";
  }
  return (
    <div className={demoClassName}></div>
  )
}

抛却局部css的概念不说,这样子写的代码好搓啊!肯定有更好的解决方案,后来我在这里找到了答案。大概的样子是这样的。

render: function() {
  var cx = React.addons.classSet;
  var demoClassName = cx({
    'wrap': true,
    'active': this.props.active,
  });
  // same final string, but much cleaner
  return <div className={demoClassName}></div>;
}

不过应该存在将局部css和这种动态加载类名结合起来的方法,以后有时间要研究一下。

@AnLuoRidge
Copy link

主流方案是用 classnames 这个库吧。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants