我对React比较陌生,我正在尝试获取一个NavItem组件,我告诉它的子SubMenu在NavItem上空盘旋时打开。
我的问题是我正在尝试使用CSS过渡来为子菜单开放设置动画。转换在子子菜单内部,所以我传入一个布尔道具,父NavItem将使用setState更新。
转换不起作用,因为它不再调用componentWillReceiveProps而是再次调用子构造函数。
constructor(props) {
super(props);
this.handleMouseOver = this.handleMouseOver.bind(this);
this.handleMouseExit = this.handleMouseExit.bind(this);
this.state = {
isSelected: false
};
}
handleMouseOver() {
this.setState((prevState)=>{
return({
isSelected: true
});
});
}
handleMouseExit() {
console.log("Mouse Has Exited");
this.setState((prevState)=>{
return({
isSelected: false
});
});
}
render() {
let sublinksExist = this.props.link.sublinks.length > 0;
const CBNavLink = styled.li`
background-color: #777;
color: white;
display:block;
list-style-type:none;
text-transform:uppercase;
height: inherit;
:hover {
background-color: #ddd;
}
`;
const CBLinkContainer = styled.div`
height: inherit;
a {
height: inherit;
min-width: 150px;
color:inherit;
display:flex;
justify-content: center;
align-items: center;
text-decoration:none;
}
`;
const CBNavItemTitle = styled.div`
min-width: 150px;
display: flex;
color:inherit;
height: inherit;
align-items: center;
justify-content: center;
`;
return (
<CBNavLink onMouseEnter={this.handleMouseOver} onMouseLeave={this.handleMouseExit}>
<CBLinkContainer><Link linkDetails={this.props.link}/></CBLinkContainer>
<SubMenu isOpen={this.state.isSelected} orientation={this.props.orientation} level={0} links={this.props.link.sublinks}/>
</CBNavLink>
)
}
有人可以帮我弄清楚我做错了什么吗? 干杯
编辑: 这也是subMenu组件。
constructor(props) {
super(props);
console.log("SubMenu Constructor");
console.log(props.level);
this.state= {
isOpen: this.props.isOpen
}
}
componentWillReceiveProps(nextProps) {
this.setState({
isOpen: nextProps.isOpen
});
}
render() {
var translateAmount = this.props.level == 0 ? 0 : 300;
if(this.props.orientation == "right") {
if(this.props.level == 0) {
translateAmount -= 150;
}
else {
translateAmount = -translateAmount;
}
}
const CBSubMenu = styled.ul`
width: ${props => props.isOpen ? '300px' : '0px'};
display: ${this.state.isOpen ? "block" : "none"}};
position:absolute;
padding-left: 0;
transition: width 300ms ease-in;
transform: translate(${translateAmount}px);
color:#fff;
@media (min-width: 800px) {
padding-left:0;
}
`;
const subMenuItems = this.props.links.map((link, index) => {
return <SubMenuItem orientation={this.props.orientation} level={this.props.level} link={link}/>;
});
return(<CBSubMenu isOpen={this.state.isOpen}>{subMenuItems}</CBSubMenu>);
}
每次我将鼠标悬停在navItem上时,它会将“SubMenu Constructor”打印到控制台,我无法找出原因。