简体   繁体   English

如何在React中为列表元素定义CSS类?

[英]How to define css class for list element in React?

I have a list of domains in my UI. 我的UI中有一个域列表。 Every domain is a button (it can be clicked and get .active css style). 每个域都是一个按钮(可以单击并获得.active CSS样式)。 The domains names are coming from server, I get them in componentDidMount() method. 域名来自服务器,我通过componentDidMount()方法获得它们。 So I don't know the quantity of future buttons (domains) in component construct moment. 因此,我不知道组件构造时刻中未来按钮(域)的数量。

My goal is to change button style on a user click (add .active css class). 我的目标是更改用户单击时的按钮样式(添加.active CSS类)。 The first button should be active by default. 默认情况下,第一个按钮应处于活动状态。 I can identify buttons by index in array. 我可以通过数组中的索引来识别按钮。 So my code looks like this: 所以我的代码看起来像这样:

constructor(props) {
    super(props)
    this.state = {
        domainClasses: {}
    }
}

And in componentDidMount() method: componentDidMount()方法中:

componentDidMount() {
    this.props.domains.forEach((data, i) => {
        if (i === 0) {
            this.setState({
                ...this.state.domainClasses,
                [i]: `title active`
            });
        } else {
            this.setState({
                ...this.state.titleClasses,
                [i]: `title`
            });
        }
    });
}

I thought that setState() method will add numeric property in state object and then I can manipulate style on button classes. 我以为setState()方法将在state对象中添加数字属性,然后可以在按钮类上操纵样式。 But it doesn't! 但事实并非如此! I tested - if state doesn't contain numeric property in component construct moment it will ignore it in setState in future. 我测试了-如果state在组件构造时不包含数字属性,则它将在以后的setState中将其忽略。

To resole it I could add every numeric property to state object in constructor method in forEach cycle but I don't know the quantity of domains until they come from server in componentDidMount ... 为了重述它,我可以在forEach周期的构造函数方法中向state对象添加每个数值属性,但是直到域来自于componentDidMount服务器,我才知道域的数量...

So, my question is - how to change css classes on button click if this buttons in list and the quantity is undefined until server response? 所以,我的问题是-如果此按钮在列表中并且数量未定义,直到服务器响应,如何在单击按钮时更改CSS类?

Any help, please! 任何帮助,请!

You are storing a possible huge state for just setting the active class for a button, why not just use something simple like activeButtonIdx 您正在存储一个可能的巨大状态,仅用于为按钮设置活动类,为什么不只使用诸如activeButtonIdx这样的简单类

in constructor, your init state will be 在构造函数中,您的init状态将是

this.state = {
  activeButtonIdx : 0
}

Inside ur render function, you can just give the class (Assume it is inside a map since you mentioned that you have a list of buttons) 在ur渲染函数中,您可以仅提供类(假设它在地图中,因为您提到您具有按钮列表)

{
  buttons.map((d, i) => <Button className={this.state.activeButtonIdx === i ? 'active title' : 'title' } onClick={() => this.setState({activeButtonIndex : i})} key={d.id}/>)
}

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

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