我目前正在构建一个下拉按钮来学习React.我在父div中创建了两个onMouseEnter和onMouseLeave事件,使其在悬停时可见,而不是.问题是这些事件只会影响父母.
如何使用React中的onMouseLeave包含子上下文?
或者,当我在徘徊在孩子身上时,如何保持状态扩展?
class DropDownButton extends React.Component { constructor(){ super(); this.handleHoverOn = this.handleHoverOn.bind(this); this.handleHoverOff = this.handleHoverOff.bind(this); this.state = {expand: false}; } handleHoverOn(){ if(this.props.hover){ this.setState({expand: true}); } } handleHoverOff(){ if(this.props.hover){ this.setState({expand: false}); } } render() { return ( <div> <div className={styles.listTitle} onMouseEnter={this.handleHoverOn} onMouseLeave={this.handleHoverOff}> {this.props.name} </div> <div> {React.Children.map(this.props.children,function(child){ return React.cloneElement(child,{className: 'child'}); })} </div> </div> ); } }
你的DOM中有两个不重叠的div;我会拆分渲染,所以更明显:
原文链接:https://www.f2er.com/react/300885.htmlrender() { return ( <div> <div className={styles.listTitle} onMouseEnter={this.handleHoverOn} onMouseLeave={this.handleHoverOff}> {this.props.name} </div> <div> {React.Children.map(this.props.children,function(child){ return React.cloneElement(child,{className: 'child'}); })} </div> </div> ); }
附加了onMouseLeave的div不包含子项;所以,当鼠标移动到孩子上时,它会离开div并调用this.handleHoverOff.
您可以考虑使用CSS隐藏子项,如果它们不应显示或有条件地呈现它们:
render() { return ( <div className={styles.listTitle} onMouseEnter={this.handleHoverOn} onMouseLeave={this.handleHoverOff}> {this.props.name} {this.state.expanded && this.renderChildren()} </div> ); },renderChildren() { return ( <div> {React.Children.map(this.props.children,function(child){ return React.cloneElement(child,{className: 'child'}); })} </div> ); }