Javascript 如何使用 React.js 添加一个类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33262493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:52:31  来源:igfitidea点击:

How to add a class with React.js?

javascriptjqueryreactjs

提问by

I need add class "active" after click to button and remove all other "active" classes.

我需要在单击按钮后添加“活动”类并删除所有其他“活动”类。

Look here please: https://codepen.io/azat-io/pen/RWjyZX

请看这里:https: //codepen.io/azat-io/pen/RWjyZX

var Tags = React.createClass({
  setFilter: function(filter) {
    this.props.onChangeFilter(filter);
  },
  render: function() {
    return <div className="tags">
      <button className="btn active" onClick={this.setFilter.bind(this, '')}>All</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'male')}>male</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'female')}>female</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'child')}>child</button>
      <button className="btn" onClick={this.setFilter.bind(this, 'blonde')}>blonde</button>
     </div>
  }
});

var Kid = React.createClass({
  render: function() {
    return <ul>
      <li>{this.props.name}</li>
      </ul>
  }
});

var List = React.createClass({
  getInitialState: function() {
    return {
      filter: ''
    };
  },
  changeFilter: function(filter) {
    this.setState({
      filter: filter
    });
  },
  render: function() {
    var list = this.props.Data;

    if (this.state.filter !== '') {
      list = list.filter((i)=> i.tags.indexOf(this.state.filter) !== -1);
      console.log(list);
    } 

    list = list.map(function(Props){
      return <Kid {...Props} />
    });

    return <div>
      <h2>Kids Finder</h2>
      <Tags onChangeFilter={this.changeFilter}/>
      {list}
    </div>
  }
});

var options = {
  Data:  [{
    name: 'Eric Cartman',
    tags: ['male', 'child']
  },{
    name: 'Wendy Testaburger',
    tags: ['female', 'child']
  },{
    name: 'Randy Marsh',
    tags: ['male']
  },{
    name: 'Butters Stotch',
    tags: ['male', 'blonde', 'child']
  },{
    name: 'Bebe Stevens',
    tags: ['female', 'blonde', 'child']
  }]
};

var element = React.createElement(List, options);
React.render(element, document.body);

How do I make it better here?

我如何让它在这里变得更好?

采纳答案by Dayan Moreno Leon

It is simple. take a look at this

很简单。看看这个

https://codepen.io/anon/pen/mepogj?editors=001

https://codepen.io/anon/pen/mepogj?editors=001

basically you want to deal with states of your component so you check the currently active one. you will need to include

基本上你想处理你的组件的状态,所以你检查当前活动的状态。你需要包括

getInitialState: function(){}
//and 
isActive: function(){}

check out the code on the link

查看链接上的代码

回答by tomasbarrios

this is pretty useful:

这非常有用:

https://github.com/JedWatson/classnames

https://github.com/JedWatson/classnames

You can do stuff like

你可以做这样的事情

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

or use it like this

或者像这样使用它

var btnClass = classNames('btn', this.props.className, {
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});

回答by RayLoveless

Taken from their site.

取自他们的网站。

render() {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

https://reactjs.org/docs/faq-styling.html

https://reactjs.org/docs/faq-styling.html

回答by wintvelt

Since you already have <Tags>component calling a function on its parent, you do not need additional state: simply pass the filter to the <Tags>component as a prop, and use this in rendering your buttons. Like so:

由于您已经有<Tags>组件在其父级上调用函数,因此您不需要额外的状态:只需将过滤器<Tags>作为道具传递给组件,并在渲染按钮时使用它。像这样:

Change your render function inside your <Tags>component to:

<Tags>组件内的渲染函数更改为:

render: function() {
  return <div className = "tags">
    <button className = {this._checkActiveBtn('')} onClick = {this.setFilter.bind(this, '')}>All</button>
    <button className = {this._checkActiveBtn('male')} onClick = {this.setFilter.bind(this, 'male')}>male</button>
    <button className = {this._checkActiveBtn('female')} onClick = {this.setFilter.bind(this, 'female')}>female</button>
    <button className = {this._checkActiveBtn('blonde')} onClick = {this.setFilter.bind(this, 'blonde')}>blonde</button>
  </div>
},

And add a function inside <Tags>:

并在里面添加一个函数<Tags>

_checkActiveBtn: function(filterName) {
  return (filterName == this.props.activeFilter) ? "btn active" : "btn";
}

And inside your <List>component, pass the filter state to the <tags>component as a prop:

<List>组件内部,将过滤器状态<tags>作为 prop传递给组件:

return <div>
  <h2>Kids Finder</h2> 
  <Tags filter = {this.state.filter} onChangeFilter = {this.changeFilter} />
  {list}
</div>

Then it should work as intended. Codepen here(hope the link works)

然后它应该按预期工作。Codepen在这里(希望链接有效)