【发布时间】:2022-10-15 16:29:07
【问题描述】:
我想将一个函数从一个反应组件传递给另一个函数。由于我需要使用 GraphQL 查询,因此该函数不允许作为反应组件,因为不允许在组件中定义反应挂钩。但是当我只是将函数作为参数传递时,我收到错误“handleSomething 不是函数”。有没有办法做到这一点,还是我需要调整结构?我的主要目标是进行突变,然后更改状态,以便被调用的函数将是一种关闭。例如,如果 hello 为 false,则不会调用 TestFunction。
例子 :
export class TestClass extends React.Component{
constructor(props) {
super(props);
this.handleSomething= this.handleSomething.bind(this);
this.state = {
hello: true;
};
}
handleSomething(){
this.setState({hello:false});
}
render(){
return(
<div>
...
<TestFunction handleSomething={this.handleSomething}/>
...
</div>
)
}
}
function TestFuntion(handleSomething){
const [ testMutation, { loading, error, data}] = useMutation(TEST_MUTATION);
if (loading) return 'Submitting...';
if (error) return `Submission error! ${JSON.stringify(error, null, 2)}`;
if(data != undefined) handleSomething();
return(
//here the mutation will be done
)
}
【问题讨论】:
标签: javascript reactjs react-hooks components