调用带参数的函数,并在按钮按下时返回值。

huangapple go评论67阅读模式
英文:

call function with parameters and return value on button press

问题

我已经创建了一个函数,该函数向我的Node.js服务器发送请求,并传递一些参数(用户名、密码等),然后返回响应状态。我想要一个按钮来激活这个函数,并使用文本框中的文本作为参数,根据函数的返回值来改变我的应用程序的行为。当我像这样做的时候:

<Button
  title="send"
  onPress={console.log(sendCreateUser("testabsdf", "test", "test", "password"))}
/>;

这个函数在页面加载时就会打开,而不是在按钮按下时,而且它总是打印undefined,即使如果我用console.log而不是返回响应状态,它就能正常工作。我只想在未收到状态码201时向用户显示错误消息,并在按下按钮后接收用户输入并将其包含在我的fetch-post请求中。

英文:

I have created a function that sends a request to my nodejs server and takes some parameters (username password etc.) and returns the response status. I would like to have a button activate the function and use text from text boxes to put in the parameters and change the behavior of my app based on the return value of the function. When I do something like this for instance

&lt;Button
  title=&quot;send&quot;
  onPress={console.log(sendCreateUser(&quot;testabsdf&quot;, &quot;test&quot;, &quot;test&quot;, &quot;password&quot;))}
/&gt;;

The function opens the second the page is loaded, not when the button is pressed, and it always prints undefined, even though if instead of returning the response.status I use console.log it will work perfectly. I just want to give the user an error message if I don't get the status 201, and I want to take user input and include it in my fetch-post to my server after a button press

答案1

得分: 1

通常 onPress 函数需要是一个回调:

onPress={() => sendCreateUser('testabsdf', 'test', 'test', 'password')}
英文:

Usually onPress function needs to be a callback :

onPress={()=&gt;sendCreateUser(&#39;testabsdf&#39;,&#39;test&#39;,&#39;test&#39;,&#39;password&#39;)}

huangapple
  • 本文由 发表于 2023年2月19日 11:47:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定