0
点赞
收藏
分享

微信扫一扫

react native中使用fetch做get请求和post请求

get请求:

import React, { useState, useRef, useEffect } from 'react'
import { View, TextInput, Text, Button } from 'react-native'
import style from './static/style'

export default function App() {
const [username, setUsername] = useState('admin')
const [password, setPasswork] = useState('123456')
const usernameEl = useRef(null)

const handleInput = (e) => {
console.log(e)
setUsername(e)
}

const handleLogin = () => {
console.log(777, username, password)
fetch('http://10.3.138.173:81/api/getUserInfo').then(res => res.json()).then(res => {
console.log(res)
})
}

useEffect(() => {
//usernameEl.current.focus()
//console.log(666, usernameEl.current.isFocused())
}, [])

return (
<View style={style.mLoginWrap}>
<View style={style.mLoginRow}>
<TextInput
style={style.mLoginInput}
value={username}
onChangeText={handleInput}
// autoFocus
ref={usernameEl}
></TextInput>
</View>
<View style={style.mLoginRow}>
<TextInput
style={style.mLoginInput}
value={password}
onChangeText={setPasswork}
secureTextEntry={true}
></TextInput>
</View>
<View style={style.mLoginRow}>
<Button onPress={handleLogin} title="登录"></Button>
</View>
</View>
)
}

post请求:

import React, { useState, useRef, useEffect } from 'react'
import { View, TextInput, Text, Button } from 'react-native'
import style from './static/style'

export default function App() {
const [username, setUsername] = useState('admin')
const [password, setPasswork] = useState('123456')
const usernameEl = useRef(null)

const handleInput = (e) => {
console.log(e)
setUsername(e)
}

const handleLogin = () => {
console.log(777, username, password)
fetch('http://10.3.138.173:81/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({username, password})
}).then(res => res.json()).then(res => {
console.log(res)
})
}

useEffect(() => {
//usernameEl.current.focus()
//console.log(666, usernameEl.current.isFocused())
}, [])

return (
<View style={style.mLoginWrap}>
<View style={style.mLoginRow}>
<TextInput
style={style.mLoginInput}
value={username}
onChangeText={handleInput}
// autoFocus
ref={usernameEl}
></TextInput>
</View>
<View style={style.mLoginRow}>
<TextInput
style={style.mLoginInput}
value={password}
onChangeText={setPasswork}
secureTextEntry={true}
></TextInput>
</View>
<View style={style.mLoginRow}>
<Button onPress={handleLogin} title="登录"></Button>
</View>
</View>
)
}

react native中使用fetch做get请求和post请求_json

 


举报

相关推荐

0 条评论