2017-04-13 78 views
0

我有這2個組件,我想知道如何調用傳遞的函數。因爲如果我通過它 - >我有一個孩子的參考,所以當我想要傳遞一個參數時會出現問題 - 因爲它立即調用(這很明顯)。如何正確調用子組件中的傳遞函數

class Parent extends Component { 
    .... 
    fn = (arg) => {console.log(arg)} 
    render(){ 
    return (
     <Child myPassedFn={this.fn}>delete</button> 
    ) 
    } 
} 

class Child extends Component { 
render(){ 
    return (
     <button onClick={this.props.myPassedFn('lul')}>delete</button> 
    ) 
    } 
} 
這樣

只要成分Child渲染,myPassedFn將執行

所以這是讓它發生一個正確的做法?因爲我想讓認爲,你知道,在一個最清晰和正確的方式

class Child extends Component { 

childFn =() => { 
    this.props.myPassedFn('this is how i could pass, you little..') 
} 
render(){ 
    return (
     <button onClick={this.childFn}>delete</button> 
    ) 
    } 
} 

回答

1

你可以把它寫這樣也:

onClick={() => this.props.myPassedFn('lul')} 

Onclick除外method的方式,以及你正在使用是,方法調用,它將爲return的值。

你也可以使用第二種方式,上面的一行就是簡寫。

+0

really appriciate =) – ddeadlink

+0

在'render'內定義匿名函數將使得使用'shouldComponentUpdate'優化兒童渲染變得困難,因爲'onClick'道具將在每個渲染中發生變化。更好的方法是在每次組件呈現時使用相同的處理程序來定義'_handleClick'處理程序 – thedude

相關問題