首頁  >  文章  >  web前端  >  React中元件事件使用詳解

React中元件事件使用詳解

php中世界最好的语言
php中世界最好的语言原創
2018-05-24 14:28:041469瀏覽

這次帶給大家React中元件事件使用詳解,React中元件事件使用的注意事項有哪些,下面就是實戰案例,一起來看一下。

事件和ref

事件可以直接寫入DOM 節點,然後透過ref 來取得DOM 節點

import React from 'react';
import ReactDOM from 'react-dom';
class Component1 extends React.Component{
    focusHandler(){
        this.refs.name.focus();
    }
    render(){
        return (
            <p>
                <input type="text" name="name" placeholder="" ref="name"/>
                <input type="button" name="" value="focus" onClick={this.focusHandler} />
            </p>
        );
    }
};
ReactDOM.render(<Component1/>, document.getElementById('p1'));

效果預覽

事件物件- event

React 在事件方法呼叫上預設會傳一個形參events,該物件是一個合成事件,所以不需要擔心瀏覽器相容的問題。

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 指標能正確指回元件物件本身,通常可以用下面幾種方法。

事件定義使用箭頭函數

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)}/>
    }
}

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

react實作選取li高亮步驟詳解

JS中使用介面步驟詳解

以上是React中元件事件使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn