![](/img/trans.png)
[英]Getting a typeError in React saying this.props is not a function when child component tries to call passed function
[英]Getting this.props is not function when passes function to child React
我想將一個函數從父(PendingRides)傳遞給子(ThirdSidebar)
但是出現錯誤_this.props.onclk不是一個函數。我已經綁定了這個函數但仍然出錯。
class PendingRides extends React.Component {
//Parent Class
constructor(props) {
super(props);
this.switchclk=this.switchclk.bind(this);
this.state={
clk:false
}
}
switchclk = (status)=>{
console.log("Here2");
this.setState({clk:status})
};
render(){
return(
<div>
<ThirdSidebar onclk={this.switchclk}/> // passing function to child
{this.state.clk ?
<div>
<div className="layout-content">
<div className="layout-content-body">
</div>
</div>
</div>
:null}
</div>
)
}
}
class ThirdSidebar extends React.Component{
constructor(props){
super(props);
this.showRides=this.showRides.bind(this);
this.state={
}
}
showRides = (e)=>{
e.preventDefault();
console.log("Here1");
this.props.onclk(true)
};
render(){
let hreflink=null;
return(
<div>
<div className="layout-main"> {/*---------------------- sidebar ----------------------- */}
<div className="layout-sidebar">
<div className="layout-sidebar-backdrop">
</div>
<div className="layout-sidebar-body">
<div className="custom-scrollbar">
<nav id="sidenav" className="sidenav-collapse collapse">
<ul className="sidenav-subnav">
<li className="sidenav-subheading">Dashboards</li>
<li onClick={(e)=>this.showRides(e)} className="active"><a href={hreflink}>Pending Rides</a></li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div> {/* sidebar ends */}
</div>
</div>
)
}
}
導出默認的ThirdSidebar
當用戶單擊掛起的游樂設施時,它將調用showRides函數,在該函數中我會收到道具並在子組件中出錯
在您的PendingRides
組件中,您的switchclk
函數應為:
switchclk(status){ //Remove arrow function
console.log("Here2");
this.setState({clk:status})
};
在ThirdSidebar
組件中, showRides
函數應該是這個,
showRides(e){ //Remove arrow function
e.preventDefault();
console.log("Here1");
this.props.onclk(true)
};
這樣調用上面的函數,
<li onClick={this.showRides} className="active"><a href={hreflink}>Pending Rides</a></li>
注意: 如何使用箭頭功能
如果使用箭頭功能,則不再需要綁定功能。 實際上,箭頭函數等效於bind()
。
刪除綁定線:
this.showRides = this.showRides.bind(this); // to remove
或使用以下命令更改箭頭功能:
showRides (e) {
e.preventDefault();
console.log("Here1");
this.props.onclk(true)
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.