react 中的绑定事件
handleOpen = (e)=> {
this.setState({
open: true
})
}
<Button color='primary' onClick={this.handleOpen}>打开模态框</Button>
在构造函数里面 bing
constructor(props){
super(props);
this.handleOpen = this.handleOpen.bind(this);
}
handleOpen(e) {
this.setState({
open: true
})
}
<Button color='primary' onClick={this.handleOpen}>打开模态框</Button>
获取点击事件的元素
asd = e=>{
console.log(e.currentTarget); // div>span
console.log(e.target); // span
}
return (
<React.Fragment>
<div onClick={this.asd}><span>click me</span></div>
</React.Fragment>
);
传递参数
handleOpen = hello => ({target}) =>{
l(hello, target)
}
<Button color='primary' onClick={this.handleOpen('hello')}>打开模态框</Button>
e.preventDefault(); 阻止默认行为
e.stopPropagation() 阻止事件传播(冒泡)
支持的事件名
rxjs 防抖
<RootRef rootRef={e => this.button = e}>
<Button color='secondary'>Get Json</Button>
</RootRef>
componentDidMount() {
fromEvent(this.button, 'click')
.pipe(
throttleTime(2000))
.subscribe(async v => {
let res = await ajax('http://localhost:1995/a')
.pipe(map(res => res.response))
.toPromise();
store
.state
.users
.push(res)
})
}
lodash 防抖
// 带参数
<Button color='secondary' onClick={this.handleClick('ajanuw')}>Get Json</Button>
handleClick = (name) => throttle((e) => {
l(name)
}, 2000)
// 不带参数
<Button color='secondary' onClick={this.handleClick}>Get Json</Button>
handleClick = throttle((e) => {
l(1)
}, 2000)
rxjs debounce
class Hello extends Component {
list = new Array(20).fill(0);
render() {
return (
<div
ref={this.props.helloRef}
style={{
width: 400,
height: 200,
border: "1px solid red",
overflow: "auto",
}}
>
{this.list.map((el, i) => (
<li key={i}>{i}</li>
))}
</div>
);
}
}
class Test extends Component {
helloRef = React.createRef();
componentDidMount() {
fromEvent(this.helloRef.current, "scroll")
.pipe(debounceTime(20))
.subscribe(v => {
l(v.target.scrollTop);
});
}
render() {
return <Hello helloRef={this.helloRef} />;
}
}