React鼠标事件

说明:假设有一个用户名片,当鼠标滑到上面,显示用户详细信息,且用户详情卡片位置随鼠标位置改变而改变。

UI框架:Material-ui

实现思路:

1.一个用户简介组件A(用于展示用户列表);

2.一个用户详情组件B(用于展示用户详情);

3.在A组件里写鼠标事件,当鼠标滑到A上,显示B组件,鼠标滑出A,隐藏B组建

鼠标事件:onMouseOver  onMouseOut

给A组件一个默认state属性,通过鼠标事件改变state值,并将state值传递给B组件

组件A

import React from \'react\';
import { Card, CardHeader, CardText } from \'material-ui/Card\';
import SocialPerson from \'material-ui/svg-icons/social/person\';
import { blue500 } from \'material-ui/styles/colors\';
import B from \'./B\';

const styles = {
   memberCardStyle: {
     marginTop:20,
     marginBottom:20,
     marginLeft:15,
     display:\'inline-block\',
     width: \'23%\'
}
}

class A extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
detailShow: \'none\',
x: 0,
y: 0
}
}

handleMouseOver = (e) => {
this.setState({
detailShow: \'block\',
x: e.pageX, //pageX是以html左上角为原点,相应的clientX是以浏览器左上角为原点
y: e.pageY,
})
}

handleMouseOut = () =>{
this.setState({
detailShow: \'none\',
x: 0,
y: 0
})
}

render() {

return (
<Paper style={styles.memberCardStyle}>
<Card
zDepth={1}
onMouseOver={this.handleMouseOver}
onMouseOut={this.handleMouseOut}
containerStyle={{paddingRight:0}}
>
<CardHeader
title="成员1"
titleStyle={{marginLeft:-10,marginTop:18,fontSize:16,paddingRight:"0 !important"}}
subtitle="gan.maoyou@datatom.com"
subtitleStyle={{marginLeft:-10,marginTop:10,paddingRight:"0 !important",fontSize:12}}
avatar={
<div style={{backgroundColor:blue500,width:60,height:70,display:\'inline-block\',textAlign:\'center\',marginLeft:-5,marginTop:-5,marginBottom:-5,}}>
<SocialPerson style={{width:60,height:70,color:\'white\'}}/>
</div>}
style={{paddingRight:"0 !important"}}
/>
</Card>

{/*将所需的值通过props传递给组件B*/}
<B     
dx={this.state.x}
dy={this.state.y}
detailShow={this.state.detailShow}
/>
</Paper>
)
}
}

export default A;

组件B

import React from \'react\';
import Card from \'material-ui/Card\';

class B extends React.PureComponent {
constructor(props) {
super(props);
}

render() {
const { dx, dy , detailShow } = this.props;

return (
<Card style={{position:\'absolute\',top: dy, left: dx, display: detailShow}}>
<ul style={{listStyleType:\'none\',padding:15}}>
<li>成员角色:普通用户</li>
<li>用户ID:1234455</li>
<li>创建时间:2017/03/01</li>
</ul>
</Card>
)
}
}

export default B;

react鼠标事件集合:https://segmentfault.com/a/1190000004642694

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwdjds.html