我的意图是在handleClick
单击相应元素时触发该方法,以便active
在false
和之间切换状态属性true
。如果在渲染内部调用是导致问题的原因,那么handleClick
在单击该元素时如何调用该方法?
import React, { Component } from 'react';
import styled from 'styled-components';
const NestedProperty = styled.div`
margin-left: 2rem;
`;
const ParentContainer = styled.div`
display: flex;
flex-direction: column;
`;
const NestedContainer = styled.div`
display: flex;
flex-direction: column;
`;
class SideMenuContainer extends Component {
constructor(props) {
super(props);
this.state = {
active: false
};
this.handleClick = this.handleClick.bind(this)
}
handleClick(){
console.log("toggle click!")
this.setState({active : !this.state.active});
}
render() {
if (this.state.active == true){
return (
<ParentContainer>
<p onClick={() => this.props.handleClick()}>{this.props.parentName}</p>
<NestedContainer>
{this.props.properties.map(propertyElement => {
return (
<NestedProperty onClick={() => { this.props.changeInfoList(propertyElement.name, propertyElement.data_type, propertyElement.app_keys.join(', '))}} >
{propertyElement.name}
</NestedProperty>
);
})}
</NestedContainer>
</ParentContainer>
);
}
else {
return (
<ParentContainer>
<p onClick={this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
}
}
export default SideMenuContainer;
这将修复它。
else {
return (
<ParentContainer>
<p onClick={() => this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
你原来有这个。
else {
return (
<ParentContainer>
<p onClick={this.handleClick()}>{this.props.parentName}</p>
</ParentContainer>
);
}
如果你打算这样做,你需要排除 () 并只做this.handleClick
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句