gpt4 book ai didi

ios - 为什么我不能在 iOS 上离开键盘以在 React Native App 中发送 Post?

转载 作者:行者123 更新时间:2023-12-04 13:50:40 26 4
gpt4 key购买 nike

bounty 3 天后到期。此问题的答案有资格获得 +150 声望奖励。
Miguel Espeso正在寻找规范的答案。







在使用 npx react-native init MyApp 创建的应用程序中
我遇到了无法纠正的问题。
我有一个部分可以将图像和文本上传到数据库 Firebase。
在屏幕上,我有一个按钮可以发送帖子,如第一张图片所示。
当我开始输入文本并且文本很丰富时,发送按钮消失了,因为我无法离开键盘,所以无法发送文本。
添加图片时也会出现这个问题,因为它占用的更多,发送按钮也消失了,我无法离开键盘。
我已将 ScroolView 添加到包含此屏幕的 View 中,但它破坏了应用程序,将项目带到屏幕顶部。
在其他屏幕上,我删除了带有功能的下方任务栏,以便为设备的键盘留出更多空间,但是这次我不知道如何解决问题。
在 iOS 中,完全不可能离开键盘来访问 Send Post 按钮。
在 Android 设备上,按钮会略微显示,正如我在 Android 图像中显示的那样,并且当我添加文本时,屏幕也会自动滚动。
但是,在 iOS 上这不会发生,而且我无法发送 Post。
我该如何纠正这个错误?
如何让应用程序键盘在我想要的时候消失?
我用更多信息编辑问题
我尝试了用户@MichaelBahl 提供给我的解决方案,
添加KeyboardAvoidingView,并且随着文本的工作,文本始终向顶部滚动,但是如果我们添加大量文本和图像,则发送按钮在iOS和Android中都消失在底部,从而无法发送消息。
如何在 iOS 和 Android 上解决此问题?
我将继续寻找解决方案。
我添加了一个我忘记的样式文件,这些样式带有 "styled-components"是什么创造了屏幕
添加似乎有效,但是当我打开该屏幕时,按钮非常靠近顶部,并且无法显示“添加图像”按钮
我再次编辑问题
我用过 <KeyboardAwareScrollView>正如用户@MuhammadNuman 所建议的那样。
这似乎有效,但是在此屏幕上开始时,按钮位于顶部,因此阻止您使用右侧的按钮添加图像。
所有这些都可能由于我的 TextInput 中使用的样式而发生,但我不知道如何纠正它。
我展示了一个新的屏幕截图和一个带有按钮操作的视频
enter image description here
enter image description here

import React, { useContext, useState } from "react"
import {
View,
Text,
Button,
Alert,
ActivityIndicator,
ScrollView,
TouchableWithoutFeedback,
Keyboard,
KeyboardAvoidingView,
} from "react-native"

import ActionButton from "react-native-action-button"
import Icon from 'react-native-vector-icons/Ionicons'
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'
import ImagePicker from "react-native-image-crop-picker"

import storage from '@react-native-firebase/storage'
import firestore from '@react-native-firebase/firestore'

import globalStyles from "../styles/global"
import {
InputField,
InputWrapper,
AddImage,
SubmitBtn,
SubmitBtnText,
StatusWrapper
} from '../styles/AddPostStyles'
import { AuthContext } from "../navigation/AuthProvider"

const AddPostScreen = () => {
const { user, logout } = useContext(AuthContext)

const [image, setImage] = useState(null)
const [uploading, setUploading] = useState(false)
const [transferred, setTransferred] = useState(0)
const [post, setPost] = useState(null)

const takePhotoFromCamera = () => {
ImagePicker.openCamera({
width: 1200,
height: 780,
cropping: true,
}).then((image) => {
console.log(image)
const imageUri = Platform.OS === 'ios' ? image.sourceURL : image.path
setImage(imageUri)
})
}

const choosePhotoFromLibrary = () => {
ImagePicker.openPicker({
width: 1200,
height: 780,
cropping: true,
}).then((image) => {
console.log(image)
const imageUri = Platform.OS === 'ios' ? image.sourceURL : image.path
setImage(imageUri)
})
}

const submitPost = async () => {
const imageUrl = await uploadImage()
console.log('Image Url', imageUrl)

firestore()
.collection('posts')
.add({
userId: user.uid,
post: post,
postImg: imageUrl,
postTime: firestore.Timestamp.fromDate(new Date()),
likes: null,
comments: null
})
.then(() => {
console.log('Post Added...')
Alert.alert(
'Post published!',
'Your post has been published Successfully!',
)
setPost(null)
})
.catch((error) => {
console.log('Something went wrong with added post to firestore.', error)
})
}

const uploadImage = async () => {

if (image == null) {
return null
}
const uploadUri = image
let filename = uploadUri.substring(uploadUri.lastIndexOf('/') + 1)

// Add timestad to File Name
const extension = filename.split('.').pop()
const name = filename.split('.').slice(0, -1).join('.')
filename = name + Date.now() + '.' + extension

setUploading(true)
setTransferred(0)

const storageRef = storage().ref(`photos/${filename}`)

const task = storageRef.putFile(uploadUri)
// Set transferred state
task.on('state_changed', (taskSnapshot) => {
console.log(`${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}`)

setTransferred(
Math.round(taskSnapshot.bytesTransferred / taskSnapshot.totalBytes) * 100
)
})

try {
await task

const url = await storageRef.getDownloadURL()
setUploading(false)
setImage(null)
/* Alert.alert(
'Imagen subida!',
'Tu imagen se subio correctamente!',
) */
return url

} catch (e) {
console.log(e)
return null
}

}

return (
<KeyboardAvoidingView
behavior={Platform.OS === "android" ? "padding" : "height"}
style={{ flex: 1 }}>

<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={globalStyles.container}>

<InputWrapper>
{image != null ? <AddImage source={{ uri: image }} /> : null}
<InputField
placeholder="¿Qué tienes en mente?"
multiline
numberOfLines={4}
value={post}
onChangeText={(content) => setPost(content)}
/>
{uploading ? (
<StatusWrapper>
<Text>{transferred} % Completed!</Text>
<ActivityIndicator size="large" color="#27AE60" />
</StatusWrapper>
) : (
<SubmitBtn onPress={submitPost}>
<SubmitBtnText>Post</SubmitBtnText>
</SubmitBtn>
)}
</InputWrapper>

<ActionButton buttonColor="rgb(26, 188, 156)">
<ActionButton.Item
buttonColor='#9b59b6'
title="New Task" onPress={() => console.log("notes tapped!")}>
<Icon name="md-create" style={globalStyles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item
buttonColor='#3498db'
title="Take Photp"
onPress={takePhotoFromCamera}>
<Icon name="camera-outline" style={globalStyles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item
buttonColor='#1abc9c'
title="Elegir"
onPress={choosePhotoFromLibrary}>
<Icon name="md-images-outline" style={globalStyles.actionButtonIcon} />
</ActionButton.Item>
</ActionButton>

</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
)
}

export default AddPostScreen
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}})

export default KeyboardAvoidingComponent
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here
代码:
import React, { useContext, useState } from "react"
import { View, Text, Button, Alert, ActivityIndicator, ScrollView } from "react-native"

import ActionButton from "react-native-action-button"
import Icon from 'react-native-vector-icons/Ionicons'
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'
import ImagePicker from "react-native-image-crop-picker"

import storage from '@react-native-firebase/storage'
import firestore from '@react-native-firebase/firestore'

import globalStyles from "../styles/global"
import {
InputField,
InputWrapper,
AddImage,
SubmitBtn,
SubmitBtnText,
StatusWrapper
} from '../styles/AddPostStyles'
import { AuthContext } from "../navigation/AuthProvider"

const AddPostScreen = () => {
const { user, logout } = useContext(AuthContext)

const [image, setImage] = useState(null)
const [uploading, setUploading] = useState(false)
const [transferred, setTransferred] = useState(0)
const [post, setPost] = useState(null)

const takePhotoFromCamera = () => {
ImagePicker.openCamera({
width: 1200,
height: 780,
cropping: true,
}).then((image) => {
console.log(image)
const imageUri = Platform.OS === 'ios' ? image.sourceURL : image.path
setImage(imageUri)
})
}

const choosePhotoFromLibrary = () => {
ImagePicker.openPicker({
width: 1200,
height: 780,
cropping: true,
}).then((image) => {
console.log(image)
const imageUri = Platform.OS === 'ios' ? image.sourceURL : image.path
setImage(imageUri)
})
}

const submitPost = async () => {
const imageUrl = await uploadImage()
console.log('Image Url', imageUrl)

firestore()
.collection('posts')
.add({
userId: user.uid,
post: post,
postImg: imageUrl,
postTime: firestore.Timestamp.fromDate(new Date()),
likes: null,
comments: null
})
.then(() => {
console.log('Post Added...')
Alert.alert(
'Post published!',
'Your post has been published Successfully!',
)
setPost(null)
})
.catch((error) => {
console.log('Something went wrong with added post to firestore.', error)
})
}

const uploadImage = async () => {

if (image == null) {
return null
}
const uploadUri = image
let filename = uploadUri.substring(uploadUri.lastIndexOf('/') + 1)

// Add timestad to File Name
const extension = filename.split('.').pop()
const name = filename.split('.').slice(0, -1).join('.')
filename = name + Date.now() + '.' + extension

setUploading(true)
setTransferred(0)

const storageRef = storage().ref(`photos/${filename}`)

const task = storageRef.putFile(uploadUri)
// Set transferred state
task.on('state_changed', (taskSnapshot) => {
console.log(`${taskSnapshot.bytesTransferred} transferred out of ${taskSnapshot.totalBytes}`)

setTransferred(
Math.round(taskSnapshot.bytesTransferred / taskSnapshot.totalBytes) * 100
)
})

try {
await task

const url = await storageRef.getDownloadURL()
setUploading(false)
setImage(null)
/* Alert.alert(
'Imagen subida!',
'Tu imagen se subio correctamente!',
) */
return url

} catch (e) {
console.log(e)
return null
}

}

return (
<View style={globalStyles.container}>

<InputWrapper>
{image != null ? <AddImage source={{ uri: image }} /> : null}
<InputField
placeholder="¿Qué tienes en mente?"
multiline
numberOfLines={4}
value={post}
onChangeText={(content) => setPost(content)}
/>
{uploading ? (
<StatusWrapper>
<Text>{transferred} % Completed!</Text>
<ActivityIndicator size="large" color="#27AE60" />
</StatusWrapper>
) : (
<SubmitBtn onPress={submitPost}>
<SubmitBtnText>Post</SubmitBtnText>
</SubmitBtn>
)}
</InputWrapper>

<ActionButton buttonColor="rgb(26, 188, 156)">
<ActionButton.Item
buttonColor='#9b59b6'
title="New Task" onPress={() => console.log("notes tapped!")}>
<Icon name="md-create" style={globalStyles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item
buttonColor='#3498db'
title="Take Photp"
onPress={takePhotoFromCamera}>
<Icon name="camera-outline" style={globalStyles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item
buttonColor='#1abc9c'
title="Elegir"
onPress={choosePhotoFromLibrary}>
<Icon name="md-images-outline" style={globalStyles.actionButtonIcon} />
</ActionButton.Item>
</ActionButton>

</View>


)
}

export default AddPostScreen
//////////////////////////
import styled from 'styled-components'

export const InputWrapper = styled.View`
flex: 1;
justify-content: center;
align-items: center;
width: 100%;
background-color: #2e64e515;
`

export const InputField = styled.TextInput`
justify-content: center;
align-items: center;
font-size: 24px;
text-align: center;
width:90%;
margin-bottom: 15px;
`

export const AddImage = styled.Image`
width: 100%;
height: 250px;
margin-bottom: 15px;
`

export const StatusWrapper = styled.View`
justify-content: center;
align-items: center;
`

export const SubmitBtn = styled.TouchableOpacity`
flex-direction: row;
justify-content: center;
background-color: #2e64e515;
border-radius: 5px;
padding: 10px 25px;
`

export const SubmitBtnText = styled.Text`
font-size: 18px;
font-family: 'Lato-Bold';
font-weight: bold;
color: #2e64e5;
`

最佳答案

你应该使用 react-native-keyboard-aware-scroll-view

yarn add react-native-keyboard-aware-scroll-view
它将解决您的问题。
用法
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'


<KeyboardAwareScrollView>
<View>
<TextInput />
</View>
</KeyboardAwareScrollView>
注意:如果你使用 react-native<65 那么你应该使用 react-native-keyboard-aware-scroll-view@0.9.4

关于ios - 为什么我不能在 iOS 上离开键盘以在 React Native App 中发送 Post?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69849664/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com