【发布时间】: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;
`
【问题讨论】:
-
太好了,这似乎有效,当我添加它有效的代码时,它就停止了。当我添加图像和很长的文本时,按钮消失并且无法发送帖子。我将编辑这个问题,因为在 Android 中添加大量文本和图像时,会发生同样的事情。并且通过这种方式我会展示你的想法
标签: ios reactjs react-native button keyboard