Kar*_*arl 9 mouseevent reactjs
我目前正在构建一个下拉按钮来学习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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
您div的DOM中有两个不重叠的;我将分拆,render这样更加明显:
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>
);
}
Run Code Online (Sandbox Code Playgroud)
在div具有onMouseLeave连接到它不包含儿童; 因此,当鼠标悬停在孩子身上时,它将离开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>
);
}
Run Code Online (Sandbox Code Playgroud)
通过使用 on mouse leave 而不是 mouse out 并阻止孩子们的事件,无论我在列表项中移动的速度有多快,我都能可靠地工作。
| 归档时间: |
|
| 查看次数: |
21635 次 |
| 最近记录: |