我试图让我的onClick方法handleClick
设置active
和groupCardInfo
属性的状态。 active
特别是一个布尔值,我使用这个bool值来确定是否应该扩展侧面菜单项。
调用handleClick
的SideMenuContainer组件:
render() {
if (this.props.active == true){
return (
<ParentContainer>
<p onClick={this.props.handleClick(this.props.properties)}>{this.props.parentName}</p>
<NestedContainer>
{this.props.properties.map(propertyElement => {
return (
<NestedProperty onClick={() => { this.props.changeInfoList(propertyElement.name, propertyElement.data_type, propertyElement.app_keys)}} >
{propertyElement.name}
</NestedProperty>
);
})}
</NestedContainer>
</ParentContainer>
);
}
问题是单击<p>
导致handleClick
运行多次。因此,不是将active
值从false切换为true,而是将其来回切换多次,以便它再次从false返回false。
我在父App.js
中构造这个方法导致这个问题的方式有什么不对?:
handleClick(properties){
console.log("toggle click!")
// this.setState({active : !this.state.active});
this.setState({
active: !this.state.active,
groupedCardInfo: properties
})
console.log("the active state is now set to: " + this.state.active)
}
这是因为你在事件处理程序中调用该函数。 render
第一次运行它将执行您的事件处理程序。您可以像其他onClick
处理程序一样执行此操作:
<p onClick={() => { this.props.handleClick(this.props.properties) }}>{this.props.parentName}</p>
或者你可以这样做:
<p onClick={this.props.handleClick}>{this.props.parentName}</p>
但是你必须改变你在点击处理程序中引用properties
的方式。像这样:
handleClick(){
const properties = this.props.properties
this.setState({
active: !this.state.active,
groupedCardInfo: properties
})
console.log("the active state is now set to: " + this.state.active)
}
尝试使用箭头功能,就像你在其他onClick
上所做的那样:
<p onClick={() => this.props.handleClick(this.props.properties)}>
在渲染时调用this.props.handleClick...
,调用它。然后,设置状态,使组件重新渲染。