the*_*uls 22 javascript reactjs
我有一个函数,它从父级一直到组件层次结构中的子级的子级.通常这不会是一个太大的问题,但我需要从孩子那里收到一个参数.我目前收到此错误消息:Uncaught(在promise中)TypeError:this.props.myFunction不是函数.
这是我正在做的一个示例代码:
class SomeComponent extends Component{
constructor(props){
super(props);
//does whatever stuff
this.myFunction = this.myFunction.bind(this);
}
//(only applicable to raw and normal forms)
myFunction(param){
console.log('do something: ', param);
}
render(){
return (<div><ChildComponent1 myFunction={()=>this.myFunction()}/></div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 myFunction={()=>this.props.myFunction()}/></div>)
}
}
class ChildComponent2{
render(){
return (<Button onClick={()=>this.props.myFunction(param)}>SomeButton</Button>)
}
}
Run Code Online (Sandbox Code Playgroud)
所以只是为了解决这个问题:我将myFunction作为道具从SomeComponent一直传递到ChildComponent2,我希望只要点击一个按钮就调用它,并从ChildComponent2传递参数.
谢谢!
Fel*_*ing 43
我不明白你为什么会得到这个错误,但你应该做的myFunction={this.myFunction}和myFunction={this.props.myFunction}:
class SomeComponent extends Component{
constructor(props){
super(props);
//does whatever stuff
this.myFunction = this.myFunction.bind(this);
}
//(only applicable to raw and normal forms)
myFunction(param){
console.log('do something: ', param);
}
render(){
return (<div><ChildComponent1 myFunction={this.myFunction}/></div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 myFunction={this.props.myFunction}/></div>)
}
}
class ChildComponent2{
render(){
return (<Button onClick={()=>this.props.myFunction(param)}>SomeButton</Button>)
}
}
Run Code Online (Sandbox Code Playgroud)
将函数调用包含在另一个(箭头)函数中是不必要的,并且不会正确转发参数(因为所有中间箭头函数都不接受参数).
Nor*_*ldt 15
另一种和 IMO 更干净的方式来做到这一点是这样的:
class SomeComponent extends Component{
myFunction = param => {
console.log('do something: ', param);
}
render(){
return (
<div>
<ChildComponent1 onClick={this.myFunction}/>
</div>)
}
}
class ChildComponent1{
render(){
return (<div><ChildComponent2 onClick={this.props.onClick}/></div>)
}
}
class ChildComponent2{
render(){
const { onClick } = this.props // destructure
return (<Button onClick={()=>onClick(param)}>SomeButton</Button>)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52173 次 |
| 最近记录: |