React 教程第四篇 —— 組件事件

事件和 ref

事件能夠直接寫到 DOM 節點,而後經過 ref 來獲取 DOM 節點javascript

import React from 'react';
import ReactDOM from 'react-dom';

class Component1 extends React.Component{
    focusHandler(){
        this.refs.name.focus();
    }
    render(){
        return (
            <div>
                <input type="text" name="name" placeholder="" ref="name"/>
                <input type="button" name="" value="focus" onClick={this.focusHandler} />
            </div>
        );
    }
};

ReactDOM.render(<Component1/>, document.getElementById('div1'));

效果預覽html

事件對象 —— event

React 在事件方法調用上默認會傳一個形參events,該對象是一個合成事件,因此不須要擔憂瀏覽器兼容的問題。java

import React from 'react';
import ReactDOM from 'react-dom';

class Component1 extends React.Component{
    submit(e){
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={this.submit}/>
    }
}

ReactDOM.render(
    <Component1 />,
    document.getElementById('app')
)

事件 —— this 指針

在全部的事件當中,首先都要弄明白 this 指向哪裏。而 React 事件中(如上面的案例)默認的 this 都是 undefined,爲了 this 指針能正確指回組件對象自己,一般能夠用下面幾種方法。react

事件定義使用箭頭函數

class Component1 extends React.Component{
    submit = (e) => {
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={this.submit}/>
    }
}

事件調用時使用用箭頭函數

class Component1 extends React.Component{
    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={(e) => this.submit(e)}/>
    }
}

構造函數中使用 bind

class Component1 extends React.Component{
    constructor(props){
        super(props)
        this.submit = this.submit.bind(this);
    }
    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={this.submit}/>
    }
}

事件調用時用 bind

class Component1 extends React.Component{
    submit(e){
        console.log(this)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={this.submit.bind(this)}/>
    }
}

事件傳參數

事件調用時使用用箭頭函數

class Component1 extends React.Component{
    submit(e, n){
        console.log(this, n)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={(e) => this.submit(e, 100)}/>
    }
}

事件調用時用 bind

submit(n, e){
        console.log(n)
        e.target.style.color = 'red'
    }
    render(){
        return <input type="button" value="submit" onClick={this.submit.bind(this, 20)}/>
    }
}
相關文章
相關標籤/搜索