簡體   English   中英

事件對象/參數是否會自動傳遞給 React 事件處理程序?

[英]Does event object / argument get passed automatically to React event handlers?

答案很可能是,是的。 因為它有效,而且我們整天都在使用它,我知道。 我要求 %100 確定並為將來的 React 學習者提供幫助。 我在 React 的官方文檔中看不到它,除了給出一個將多個參數與事件對象一起傳遞給事件處理程序的示例 例如:正如您所看到的onFormSubmit ,雖然在 JSX 引用中沒有event參數,但它可以訪問事件對象以在執行時執行onFormSubmit操作(在此示例中阻止頁面刷新)。

如果將onFormSubmit編寫為內聯箭頭函數,如onChange處理程序,則需要傳遞事件對象,則它不是自動的。


class SearchBar extends React.Component {

     constructor(props) {
        super(props)
        this.state = { term:''}
        this.onFormSubmit = this.onFormSubmit.bind(this)
    }

    onFormSubmit(event) {
        event.preventDefault()
        console.log(this.state.term) 
    }
 
     render() {
         return (
            <div className="ui segment" >
             <form onSubmit={this.onFormSubmit} className="ui form" >
                <div className="field" >
                    <label>Search</label>
                    <input type="text" 
                    value = {this.state.term} 
                    onChange={event => this.setState({ term: event.target.value })} />
                    </div>
                 </form>
             </div>
         )
     }
 }

 export default SearchBar


您已經為onChange事件處理程序定義了函數,該函數調用 submit 方法隱式傳遞必要的參數。

React 中的event處理程序沒有什么特別之處。 每個函數(如果定義)都是這樣工作的。

const a = [1, 2, 3];

function print(elem, idx) {
    console.log(elem, idx);
}

// here you have defined the print function.
// the elem and idx are passed implicitly to run the function.
a.forEach(print);

or 

// now, rather than defining the function here.
// you have used another arrow function.
// then you need to pass the arguments explicitly.
a.forEach((elem, idx) => print(elem, idx));

React 處理事件的方式略有不同,使用合成事件,但這通常是回調處理程序的工作方式。 如果在那里使用函數引用,則event對象是傳遞給函數的唯一參數。 因此,如果事件對象是您想要獲取的唯一參數,那么您不需要使用箭頭函數。

如果您想與event對象一起傳遞其他變量,那么您可以使用箭頭函數。

<form onSubmit={e => this.onFormSubmit(e, otherVar)} className="ui form" >

因此,您的回調獲取事件參數,並將其與其他變量一起傳遞給處理程序函數。

onFormSubmit(event, otherVar) {
    event.preventDefault()
    console.log(otherVar) 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM