javascript 反应原生如何在点击 onPress 时调用多个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52250061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:52:54  来源:igfitidea点击:

react native how to call multiple functions when onPress is clicked

javascriptreactjsreact-native

提问by kirimi

I am trying to call multiple functions when I click onPressusing TouchableOpacity

单击onPressusing时,我试图调用多个函数TouchableOpacity

For example:

例如:

functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableHighlight onPress{() => this.functionOne()}/>

What if I want to call two functions when onPressis clicked? Is there a way I could call multiple functions?

如果我想在onPress单击时调用两个函数怎么办?有没有办法可以调用多个函数?

回答by Dacre Denny

There are a few ways to achieve this. One option would be to define a function that calls functionOneand functionTwo, and pass that on your onPresshandler like so:

有几种方法可以实现这一点。一种选择是定义一个调用functionOneand的函数functionTwo,并将其传递给您的onPress处理程序,如下所示:


functionOne(){
// do something
}

functionTwo(){
// do something
}

functionCombined() {
    this.functionOne();
    this.functionTwo();
}  

<TouchableHighlight onPress={() => this.functionCombined()}/>

Alternatively, and more concisely, you could express functionCombinedinline in your JSX like so:

或者,更简洁地说,您可以functionCombined像这样在 JSX 中表达内联:


functionOne(){
// do something
}

functionTwo(){
// do someting
}

<TouchableHighlight onPress={() => { this.functionOne(); this.functionTwo(); }/> 


回答by Kailash Uniyal

Recommended Solution:

推荐解决方案:

   <TouchableWithoutFeedback
    onPress={() => {
     function1();
     function2();
    }}>     

You can use these props:

你可以使用这些道具:

onPressCalled when the touch is released

onPressInCalled as soon as the touchable element is pressed and invoked before onPress.

onPress释放触摸时调用

onPressIn按下可触摸元素后立即调用并在 之前调用onPress

<TouchableWithoutFeedback
    onPress={() => {
      function1();
    }}
    onPressIn={() => {
      function2();
    }}
 >

回答by GuestReact

You can also make this with a boolean value. Example ;

您也可以使用布尔值进行设置。例子 ;

<TouchableHighlight onPress{() => { this.functionOne() || this.functionTwo()}}/>

回答by flix

Seeking your comment, you want to not used arrow, so I'm suggest to use something like this:

寻求你的评论,你不想使用箭头,所以我建议使用这样的东西:

functionOne(){
// do something
}

functionTwo(){
// do someting
}

mixFunction=()=>{
functionOne();
functionTwo();
}

mixFuncWithoutArrow(){
functionOne();
functionTwo();
}

<TouchableHighlight onPress{this.mixFunction() || this.mixFuncWithoutArrow.bind(this)}/>