需要在通过map函数reactjs编写的元素数组中触发单个元素
Posted
技术标签:
【中文标题】需要在通过map函数reactjs编写的元素数组中触发单个元素【英文标题】:Need to Trigger individual Element in an array of elements written through map function reactjs 【发布时间】:2020-02-04 16:48:15 【问题描述】:class Services extends Component
constructor(props)
super(props);
this.state = showoffer: false;
showOffers=( )=>
this.setState(showoffer: !this.state.showoffer);
render()
return (
<div className="OSServicesContainer">
<img className="OSlogomark" src=logomark />
<article className="OssHeadingText">OOM INTERIORS OFFERS</article>
offersdata.map((offers,index)=>
return ( <div key=index className="OssoffersContainermain">
<div className="OssoffersContainer">
<div className="OssofferHeadingmain">
<article className="OssofferHeading">offers.heading</article>
</div>
<article className="OssofferText">offers.subheading</article>
<div className="OssofferViewbtnmain">
<article key=index className="OssofferViewbtn" onClick=this.showOffers>this.state.showoffer?"View Less":"View More"</article>
</div>
</div>
!this.state.showoffer?
null:
<div className="OssOfferSubCompmain">
offers.offersub.map((offer,key) =>
return <OssOfferSubComp ofrtext=offer.text ofrsubtext=offer.subtext />
)
</div>
</div>
)
)
</div>);
export default Services;
以上是我的代码 我想调用 showoffer 函数并只更新点击的那个元素 请问我该怎么办它会触发所有元素 如何触发单个元素??
【问题讨论】:
【参考方案1】:你可以试试这样: `类服务扩展组件 构造函数(道具) 超级(道具); this.state = showoffer: 0;
showOffers = ( offerIndex ) =>
this.setState(showoffer: offerIndex);
hideOffers = () =>
this.setState(showoffer: 0);
render() =>
...
<div className="OssofferViewbtnmain">
<article key=index onClick= () => this.showOffers(index) >
this.state.showoffer?"View Less":"View More"
</article>
</div>
...
this.state.showOffer && this.state.showOffer === index
? // then show it
: ''
`
【讨论】:
【参考方案2】:嘿,如果您希望同时打开多个项目,您可以执行类似的操作,在其中更改映射的项目以跟踪显示隐藏状态。我在列表项中添加了一个visible
属性,用于跟踪该项是打开还是关闭:
import React, Component from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component
state =
items: [
header: "Test 1", extra: "Some extra content A" ,
header: "Test 2", extra: "Some extra content B" ,
header: "Test 3", extra: "Some extra content C"
]
;
onItemClick(index)
const selected = this.state.items[index];
this.setState(
items: [
...this.state.items.slice(0, index),
...selected, visible: !selected.visible ,
...this.state.items.slice(index + 1)
]
);
render()
return (
<div>
<ul>
this.state.items.map((item, index) =>
return (
<li
key=index
style= cursor: "pointer"
onClick=() => this.onItemClick(index)
>
<h3>item.header</h3>
item.visible ? <div>item.extra</div> : null
</li>
);
)
</ul>
</div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
https://codesandbox.io/s/busy-germain-hdmrn
【讨论】:
以上是关于需要在通过map函数reactjs编写的元素数组中触发单个元素的主要内容,如果未能解决你的问题,请参考以下文章