Javascript 根据Id隐藏元素onClick React
我有一个3个过滤器的列表,将根据他们的id显示,当点击它将显示匹配的id,但我想隐藏它,如果再次点击过滤器列表。因此,如果单击过滤器1,它应该显示,如果再次单击,它应该隐藏Javascript 根据Id隐藏元素onClick React,javascript,reactjs,Javascript,Reactjs,我有一个3个过滤器的列表,将根据他们的id显示,当点击它将显示匹配的id,但我想隐藏它,如果再次点击过滤器列表。因此,如果单击过滤器1,它应该显示,如果再次单击,它应该隐藏 import React,{Component}来自“React” 导出默认类目录扩展组件{ 建造师(道具){ 超级(道具) 此.state={ filterListShow:false, 活动:错误 } this.handleShowFilterList=this.handleShowFilterList.bind(th
import React,{Component}来自“React”
导出默认类目录扩展组件{
建造师(道具){
超级(道具)
此.state={
filterListShow:false,
活动:错误
}
this.handleShowFilterList=this.handleShowFilterList.bind(this)
}
//单击“显示过滤器清单”
handleShowFilterList(id){
这是我的国家({
filterListShow:id,
活动:false})
}
render(){
const{filterListShow}=this.state
让测试=“”
如果(filterListShow==1){
测试=(显示1)
}
else if(filterListShow==2){
test=(显示2{console.log(2)})
}
else if(filterListShow==3){
test=(显示3{console.log(3)})
}
返回(
此.handleShowFilterList(1)}>
显示过滤器1
此.handleShowFilterList(2)}>
显示过滤器2
此.handleShowFilterList(3)}>
显示过滤器3
{test}
)
}
}
只需在onClick
处理程序中添加另一个检查,以检查当前状态是否与单击的元素的id相同
// Show Filter checklist onClick
handleShowFilterList(id) {
if(this.state.filterListShow !== id) {
this.setState({
filterListShow: id,
active: false })
} else {
this.setState({filterListShow: false})
}
}
只需在
onClick
处理程序中添加另一个检查,以检查当前状态是否与单击的元素的id相同
// Show Filter checklist onClick
handleShowFilterList(id) {
if(this.state.filterListShow !== id) {
this.setState({
filterListShow: id,
active: false })
} else {
this.setState({filterListShow: false})
}
}
只需将条件放入
handleShowFilterList
功能中,如果再次单击同一项,则重置filterListShow
变量的状态值
像这样:
handleShowFilterList(id) {
this.setState(prevState => ({
//if same then reset otherwise assign new id
filterListShow: prevState.filterListShow == id ? false : id,
active: false
}))
}
只需将条件放入
handleShowFilterList
功能中,如果再次单击了同一项,则重置filterListShow
变量的状态值
像这样:
handleShowFilterList(id) {
this.setState(prevState => ({
//if same then reset otherwise assign new id
filterListShow: prevState.filterListShow == id ? false : id,
active: false
}))
}
您的问题是?您的问题是?这适用于过滤器1,但对于其他过滤器,它不会隐藏them@tomharrison抱歉,这是一个输入错误,请再次检查代码,它正在工作:)这适用于筛选器1,但对于其他筛选器,它不会隐藏them@tomharrison抱歉,是打字错误,请再次检查代码,它起作用了:)很高兴能帮上忙,伙计:)很高兴能帮上忙,伙计:)