2017-03-16 40 views
0
fireOne(){ 

} 

render(){ 
    return(
    <p onClick={this.fireOne.bind(this)}></p> 
    ) 
} 

我可以使用2個函數綁定一個事件嗎?一個函數是針對當前組件的,我也想把一些東西傳遞給子組件。在某個事件中發生火災多重功能

+1

如果你想下來的東西傳遞給孩子,那麼你可以設置的狀態點擊父組件,然後將其作爲道具傳遞給兒童。 – lavish

回答

1

我覺得這是你想acomplish什麼,但我不能完全肯定:

class MyComponent extends React.Component { 
 

 
    foo1 =() => { console.log('ahh');} 
 
    
 
    foo2 =() => { console.log('beh');} 
 
    
 
    render() { 
 
    return(<div onClick={() => { 
 
     this.foo1(); 
 
     this.foo2(); 
 
    }}>AHH </div>) 
 
    } 
 
} 
 

 
ReactDOM.render(<MyComponent />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id="root"/>

+0

爲什麼使用箭頭功能?爲什麼它不是'foo1(){...}'? –

+0

沒錯,你可以在沒有箭頭的情況下使用它,特別是如果你沒有在這裏引用'this'的話。然而,如果你不喜歡看到「function」這個詞,那麼使用箭頭函數也會起作用,它只是取決於你,只是確保你知道何時使用它。 – JohnnyQ

+0

@giala在你的問題上你有:this.fireOne.bind(this),所以我認爲你想保持上下文,這是一個更好的方式來做到這一點,性能明智。 – ospfranco