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