繁体   English   中英

如何在 React native 中调用另一个 function 中的 function

[英]How to call function inside another function in React native

如何在另一个 function 中调用一个 function? 在这里,这两个函数都是 React Native 中同一个 class 的成员。

我想在另一个 function 中调用一个 function 但它显示错误,如undefined is not a function

我该如何解决这个问题?

我的代码是:

 export default class placeOrder extends React.Component{ constructor(props) { super(props); this.state = { }; } PayNow(payM){ console.log(payM); } CODPayBtn(props) { let total = props.total; let temp = props.temp; let charge = props.charge; if(total == temp) { if(total-charge > 299) { return( <> <Button mode="contained" style={{padding:8,backgroundColor:'green',margin:8}} onPress={() => {this.PayNow('COD')}}> Cash on Delivery ( ₹{total} ) </Button> </>); } else { } } else { } } render(){ return( <SafeAreaView> <ScrollView> <View> <this.CODPayBtn total={this.state.total} temp={this.state.temp} charge={this.state.charge}/> </View> </ScrollView> </SafeAreaView> ) } }

CODPayBtn() function 中有一个按钮,如果单击此按钮,那么我想调用PayNow() function 但它给出了一个错误,即undefined is not a function

您需要将其绑定到您的 class 函数。

constructor( props ){
    super( props );
    this.PayNow = this.PayNow.bind(this);
    this.CODPayBtn = this.CODPayBtn.bind(this);
  }

或者,更好的是,使用箭头函数不必处理所有这些。

CODPayBtn = (props) => {
     let total = props.total;
     let temp = props.temp;
     let charge = props.charge;
     if(total == temp)
     { 
        if(total-charge > 299)
        {
        return(
            <>
            <Button mode="contained" style={{padding:8,backgroundColor:'green',margin:8}} onPress={() => {this.PayNow('COD')}}>
            Cash on Delivery ( ₹{total} )
           </Button>
            
              </>);
          }
          else
          {
              
          }
      }
      else
      {
       
      }

  }

发生这种情况是因为this在 js 中是如何工作的。 当 function 被定义为function (){..}时,它会失去其隐含的this并在类中设置为undefined 这就是为什么我们必须手动将它绑定到 function。或者使用没有这个问题的箭头函数。

像这样绑定你的函数:

constructor(props) {
    super(props);
    this.state = {

    };

    this.PayNow = this.PayNow.bind(this);
    this.CODPayBtn = this.CODPayBtn.bind(this);
}

尝试这个:

<View>
      {this.CODPayBtn(props)}      
</View>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM