【问题标题】:Passing a function from a react component to a function used in rendering将一个函数从一个反应组件传递给一个用于渲染的函数
【发布时间】: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


    【解决方案1】:

    您需要解构TestFucntion 中的handleSomething,因为它作为"props" 对象中的属性传递给TestFunction

    注意花括号。

      function TestFucntion({handleSomething}){
      }
    

    【讨论】:

    • 谢谢你的建议。我现在传递一个“props”参数,在其中我用 this.handle Something 声明一个句柄 Something。这样,当我调用 props.handleSomething()
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 2012-08-02
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多