如何在不使用eventandler的情况下调用props函数



我正在学习反应,并被一个问题困住了。当按钮被点击时,function3被成功调用,然而,它说this.props.function不是一个函数。我甚至把函数和这个结合起来了。然而,没有得到我错的地方。在stackoverflow上搜索了很多,但没有一个是针对我的查询。

class Parent extends Component{
constructor(props){
super(props);
this.function1 = this.function1.bind(this)
}
function1 = (someAttributes) =>{
this.setState({
//update the state
})
}
render(){
return(
<Child function={this.function1}/>
)
}
}

class Child extends Component{
constructor(props){
super(props);
this.function2 = this.function2.bind(this)
this.function3 = this.function3.bind(this) //tried this as well.
}
function2 = (someAttributes) =>{
this.props.function(someAttributes)
}
function3 = () =>{
//the logic
this.function2(someAttributes)
}

render(){
return(
<Button onClick={this.function3}/>
// even tried <Button onClick={()=>this.function3()}
)
}
}

任何帮助都是感激的!

this.function2 = this.function2.bind.this(this);应为this.function2 = this.function2.bind(this);

一切正常codesandbox

为简单起见,我使用console.log。如果需要,可以使用setState

您可以使用箭头函数,下面是您的代码的一个工作codesandbox示例。我提醒你的父函数的每一步:

沙箱

试试这个简单的方法。你不需要定义所有这些函数

class Parent extends Component{
constructor(props){
super(props);
}
function1 = (someAttributes) =>{
this.setState({
//update the state
})
}
render(){
return(
<Child function={(...params) => this.function1(...params)}/>
)
}
}

class Child extends Component{
constructor(props){
super(props);
}
function2 = (someAttributes) =>{
this.props.function(someAttributes)
}
function3 = () =>{
//the logic
this.function2(someAttributes)
}
render(){
return(
<Button onClick={() => this.function3()}/>
// even tried <Button onClick={()=>this.function3()}
)
}
}

最新更新