简体   繁体   English

React如何触发onClick从地图功能

[英]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). 我有一些被映射的列表,当我单击一个元素(它是数组中的对象之一)时,我想触发onClick。

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'. 假设有3个列表,当我单击其中的一个列表时,我想将“我单击的元素”的类从“关闭”更改为“打开”。

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 . 我有this.props.location.pathname的值,我想可以将其与Array[i].link this.props.location.pathname进行比较。

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 . 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). 状态需要保持在组件状态(或者如果复杂性成为问题,请查看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. 您不必强制性地操作DOM,也不必“询问” DOM以获取信息,而是根据状态告诉它外观。

Please have a look at this code mapping data with react elements 请看一下此代码与react元素的映射数据

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. 在这里,您可以在状态变量中使用地图,并与每个元素相关联的{key,value}对进行跟踪。 Hope this helps. 希望这可以帮助。 Thanks. 谢谢。

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

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