为啥我不能在 iOS 上离开键盘以在 React Native App 中发送帖子?
Posted
技术标签:
【中文标题】为啥我不能在 iOS 上离开键盘以在 React Native App 中发送帖子?【英文标题】:Why can't I leave the keyboard on iOS to send the Post in the React Native App?为什么我不能在 iOS 上离开键盘以在 React Native App 中发送帖子? 【发布时间】:2021-12-19 07:08:14 【问题描述】:在使用npx react-native init MyApp 创建的应用中
我遇到了无法纠正的问题。
我有一个部分可以将图像和文本上传到数据库 Firebase。 在屏幕上,我有一个发送帖子的按钮,如第一张图片所示。 当我开始输入文本并且内容丰富时,发送按钮消失,并且我无法发送文本,因为我无法离开键盘。 添加图片时也会出现问题,因为它占用更多并且发送按钮也消失了,我无法离开键盘。
我已将 ScroolView 添加到包含此屏幕的视图中,但它会破坏应用程序,将项目带到屏幕顶部。
在其他屏幕上,我删除了下方的任务栏,并带有一个功能,以便为设备的键盘提供更多空间,但这一次我不知道如何解决问题。 在 ios 中,完全不可能离开键盘来访问发送帖子按钮。 在 android 设备上,按钮会略微显示,就像我在 Android 图像中显示的那样,并且在我添加文本时屏幕会自动滚动。 但是,在 iOS 上不会发生这种情况,我无法发送帖子。 我该如何纠正这个错误? 如何让应用程序键盘在需要时消失?
我用更多信息编辑问题
我尝试了用户@MichaelBahl 提供给我的解决方案, 添加 KeyboardAvoidingView,并使用它的文本,文本总是向顶部滚动,但是如果我们添加大量文本和图像,则发送按钮在 iOS 和 Android 中都会在底部消失,从而无法发送消息。
如何在 iOS 和 Android 上解决此问题? 我会继续寻找解决方案。
我添加了一个我忘记的样式文件,这些带有"styled-components"
的样式是创建屏幕的原因
添加似乎有效,但是当我打开该屏幕时,按钮非常靠近顶部,我无法显示“添加图像”按钮
我再次编辑问题
按照用户@MuhammadNuman 的建议,我使用了<KeyboardAwareScrollView>
。
这似乎可行,但是在此屏幕上启动时,按钮位于顶部,因此阻止您使用右侧的按钮添加图像。
由于我的 TextInput 中使用的样式,所有这些都可能发生,但我不知道如何纠正它。
我展示了一个新的屏幕截图和一个带有按钮操作的视频
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
代码:
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;
`
【问题讨论】:
结帐reactnative.dev/docs/keyboardavoidingview#example 太好了,这似乎有效,当我添加它有效的代码时,它就停止了。当我添加图像和很长的文本时,按钮消失并且无法发送帖子。我将编辑这个问题,因为在 Android 中添加大量文本和图像时,会发生同样的事情。并且通过这种方式我会展示你的想法 【参考方案1】:你应该使用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-nativereact-native-keyboard-aware-scroll-view@0.9.4
【讨论】:
@MiguelEspeso 你能从 git 添加一个可重现的例子,这样我就可以检查一下吗? @MiguelEspeso 这只是一个代码文件,我想要一个包含文件导入包和 react-native 版本的整个容器应用程序 @MiguelEspeso 但来自上述要点。我必须制作 RN 项目并花费更多时间来重现问题而不是修复 我再次尝试了您的@MuhammadNuman 代码并且它可以工作,但问题是启动,它显示在屏幕的最顶部,您能以某种方式纠正这个问题吗? @MiguelEspeso 有什么更新吗?【参考方案2】:好的,我想我找到了解决方案。按照我之前提到的步骤进行操作:
yarn add react-native-keyboard-aware-scroll-view
import useRef from 'react';
import KeyboardAwareScrollView from 'react-native-keyboard-aware-scroll-view';
const scrollViewRef = useRef();
使用KeyboardAwareScrollView
并设置您刚刚声明的引用。
<KeyboardAwareScrollView ref=scrollViewRef >
<View style=flex: 1 >
//Content
</View>
</KeyboardAwareScrollView>
使用您的TextInput
(在您的情况下为InputField
),确保每次更改文本时滚动到末尾。
<TextInput
onChangeText=text =>
setText(text);
scrollViewRef.current.scrollToEnd(animated:true);
/>
应该可以。如果不是,这里是我创建的一个小吃项目,表明它可以工作https://snack.expo.dev/@bgcodes/7ff849
【讨论】:
感谢您为帮助我所做的努力。我已经尝试了您的新选项,但它不起作用。我什至对 useRef 有一个错误,尽管在 React 中调用了它,但它给出了一个错误并破坏了应用程序。我看过他的例子,但我不知道为什么它对我不起作用。我不知道该怎么办了,这有点令人沮丧,但我必须继续寻找解决方案。如果您删除任何问题,很遗憾如果您的答案不起作用,他们会给您奖励。 我不知道他们为什么会因为试图提供帮助而从我这里拿走 2 个声望点。但无论如何,如果我给你的小吃示例正在运行,但它不适用于你的项目,那么你的项目中肯定有一些东西导致了问题,如果不实际查看你的代码,我们将无法判断这些问题。抱歉,我帮不上什么忙。以上是关于为啥我不能在 iOS 上离开键盘以在 React Native App 中发送帖子?的主要内容,如果未能解决你的问题,请参考以下文章
为啥我的代码不能在 web 中的 react-native 代码中运行
如何在 React Native 中实现 Google 地图以在 Web、Android 和 iOS 上运行?
为啥我不能使用 serveo 而不是 ngrok 来隧道连接到托管在 EC2 服务器上的 mvc 应用程序以在 Twilio 上接收 SMS
React Native 为啥每次点击 textInput 时我的键盘都会立即消失?