![](/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.