首页 > 解决方案 > 如何在反应中使用带参数的函数作为道具

问题描述

如果我们使用带参数的函数并希望将此函数用作其他组件的道具,并且当我尝试console.log(this.props)在其他组件中使用时,我会得到未定义。

         anotherfunctionCall = (ss) =>  {
               console.log(ss) 
          }

     <DrawerRight
        anotherfunctionCall = {this.anotherfunctionCall('some')}

      />

当我在其他组件中控制台(this.props)时,我得到未定义。请帮助解决这个问题。如果我使用 anotherfunctionCall = (ss) => () => { console.log(ss) } 它正在工作

标签: reactjs

解决方案


我不确定这是否是您正在寻找的答案,但是您将一个函数作为道具传递给一个没有任何参数的组件。您只需传递函数引用并从带有或不带有道具的子组件中调用它。(无论你如何定义它)

anotherfunctionCall = (ss) =>  {
               console.log(ss) 
          }

     <DrawerRight
        anotherfunctionCall = {this.anotherfunctionCall}

      />

//DrawerRight.js

...

componentDidMount(){
  this.props.anotherfunctionCall("test");
}

...

推荐阅读