英文:
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
<Button
title="send"
onPress={console.log(sendCreateUser("testabsdf", "test", "test", "password"))}
/>;
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={()=>sendCreateUser('testabsdf','test','test','password')}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论