简体   繁体   中英

React How to fire onClick each from map function

I have some lists which are mapped and I'd like to fire onClick when I click an element(which is one of objects from the array).

Let's say there are 3 lists and when I click one of them, I'd like to change "the element that i clicked"'s class to 'open' from 'close'.

state= {
    open: false
}

handleClick = () => {
    this.setState({
        open: !this.state.open
    })
}

Array.map((list, index) => {
    <div key={index} onClick={this.handleClick}>
        <p className={this.state.open? 'open' : 'close'}>{list.title}</p>
    </div>
})

.

Array = [{
    title: 'a',
    link: '/service/wallet'
},{
    title: 'b',
    link: '/service/home'
}]

I have a value of this.props.location.pathname and I think I can compare this to Array[i].link .

something like this?

if(this.props.location.pathname === Array[0].link){

}

However, I don't know how to complete the code for this issue. please tell if my idea is right and some hints.

You'll need to keep the "is it clicked?" information in this.state . Because it's a list of things you need to keep track of you can't store the state in a single variable, you'll need a map of them.

state= {
    open: {}
}

handleClick = (link) => {
    let linkOpenState = false;
    if (this.state.open.hasOwnProperty(link)) {
        linkOpenState = this.state.open[link];
    }

    this.setState({ open: { [link]: linkOpenState } })
}

Array.map((list, index) => {
    <div key={index} onClick={this.handleClick.bind(this, list.link)}>
        <p className={this.state.open[list.link]? 'open' : 'close'}>{list.title}</p>
    </div>
})

You need to get used to thinking "the React way". State needs to be kept in component state (or if complexity becomes a problem then look at Redux). You don't imperatively manipulate the DOM and you don't "ask" the DOM for information, you tell it how it should look based on the state.

Please have a look at this code mapping data with react elements

To solve this problem, you can have a state which tracks the interaction for a group of elements, in your case it is list of elements. here you can use a map in a state variable and have {key,value} pair associated with each element to track it. Hope this helps. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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