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() 阻止事件傳播(冒泡) 支持的事件名javascript
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} />; } }