Javascript 更新文本后,如何在React Native中关注文本输入?

Javascript 更新文本后,如何在React Native中关注文本输入?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在用React Native和Expo创建一个聊天应用程序,现在我正在开发它的核心功能来聊天。我希望当用户发送消息时,文本输入应该自动清除。这非常有效,但当清除TextInput(其文本更新为“空字符串”)时,光标未激活意味着TextInput将丢失foucs。在我更新(清除)TextInput的文本后,是否有任何方法以编程方式关注TextInput。对于我的聊天屏幕中出现的任何错误和问题(糟糕的编码),我深表歉意,因为我是一个新手 ChatScreen的代码为: import { Stat

我正在用React Native和Expo创建一个聊天应用程序,现在我正在开发它的核心功能来聊天。我希望当用户发送消息时,文本输入应该自动清除。这非常有效,但当清除TextInput(其文本更新为“空字符串”)时,光标未激活意味着TextInput将丢失foucs。在我更新(清除)TextInput的文本后,是否有任何方法以编程方式关注TextInput。对于我的聊天屏幕中出现的任何错误和问题(糟糕的编码),我深表歉意,因为我是一个新手

ChatScreen的代码为:

import { StatusBar } from 'react-native';

import { StyleSheet, View, Platform, TextInput } from 'react-native';
import { Avatar, Appbar, IconButton } from 'react-native-paper';

import Background from '../components/FullBackground';
import Logo from '../components/Logo';
import Header from '../components/Header';
import Button from '../components/Button';
// import TextInput from '../components/TextInput';
import BackButton from '../components/BackButton';
import ProgressDialog from '../components/ProgressDialog';

import { theme } from '../core/theme';

import { connect } from 'react-redux';

import db from '../../firebase';
import { ScrollView } from 'react-native-gesture-handler';

class ChatScreen extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            uid: this.props.route.params.id,
            name: 'Name',
            status: 'Status',
            image: 'default',
            thumb_image: 'default',
            messages: [],
            new_message: {
                value: ''
            },
        }

        this.currentUserUid = this.props.user.uid;

        this.currentUserDoc = db.collection('Users').doc(this.currentUserUid);
        this.userDoc = db.collection('Users').doc(this.state.uid);

        this.currentUserChatsCollection = this.currentUserDoc.collection('chats');
        this.userChatsCollection = this.userDoc.collection('chats');

        this.userDoc.onSnapshot(snapshot => {
            if (snapshot.exists) {
                snapshot = snapshot.data();

                this.setState({
                    name: snapshot.name,
                    status: snapshot.status,
                    image: snapshot.image,
                    thumb_image: snapshot.thumb_image,
                });
            }
        });

        this.onSendButtonPressed = this.onSendButtonPressed.bind(this);
    }

    onSendButtonPressed() {
        let message = this.state.new_message.value;
        message = message.trim();

        console.log(`[DEBUG] Message: ${message}`);

        this.setState({
            new_message: {
                value: ''
            }
        });

        // I clear the text here and after that it loses focus

    }

    render() {
        return (
            <>
                <Appbar.Header style={{ paddingBottom: Platform.OS === 'android' ? 25 : 0 }}>
                    <Appbar.BackAction onPress={() => {this.props.navigation.goBack()}}/>
                    <Avatar.Image style={{ marginLeft: 2 }} size={50} source={this.state.image === 'default' ? require('../assets/avatar.png') : { uri: this.state.image }}/>
                    <Appbar.Content style={{ marginLeft: 3, marginTop: 0 }} title={this.state.name} subtitle={'Email'} />
                    <Appbar.Action color='white' icon="dots-vertical" onPress={this.openMenu} />
                            
                </Appbar.Header>

                <Background>
                    <View style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
                        <View style={{ flex: 1, display: 'flex', backgroundColor: '#fafafa' }}>
                            <ScrollView style={{ flex: 1 }}>
                                // Messages will go here which are not implemented yet
                            </ScrollView>
                        </View>

                        <View style={{ height: 70, borderTopWidth: 1, display: 'flex', flexDirection: 'row', borderTopColor: 'rgb(243, 243, 243)', paddingVertical: 10 }}>
                            <IconButton icon='sticker-emoji'/>

                            <TextInput 
                                value={this.state.new_message.value}
                                onChangeText={(text) => {
                                    this.setState({
                                        new_message: { 
                                            value: text 
                                        }
                                    });
                                }}
                                style={{ 
                                    flex: 1, 
                                    backgroundColor: 'lightgray', 
                                    borderRadius: 30, 
                                    marginVertical: 5, 
                                    paddingHorizontal: 15, 
                                    paddingVertical: 5, 
                                    outline: 'none',
                                }} 
                                autoCapitalize='sentences'
                                keyboardType='default'
                                autoCompleteType='off'
                                textContentType='none'
                                placeholder='Type the message...' 
                                placeholderTextColor='gray'
                                onKeyPress={(event) => {
                                    if (event.nativeEvent.key === 'Enter') {
                                        this.onSendButtonPressed();
                                    }
                                }}
                            />

                            <IconButton icon='attachment'/>
                            <IconButton icon='send' onPress={this.onSendButtonPressed}/>
                        </View>
                    </View>
                </Background>
            </>
        )
    }

}

const styles = StyleSheet.create({

});

const mapStateToProps = (state) => {
    const { user } = state.user;
    return { user }
};

export default connect(mapStateToProps)(ChatScreen);
从'react native'导入{StatusBar};
从“react native”导入{样式表、视图、平台、文本输入};
从“react native paper”导入{Avatar、Appbar、IconButton};
从“../components/FullBackground”导入背景;
从“../components/Logo”导入徽标;
从“../components/Header”导入标题;
从“../components/Button”导入按钮;
//从“../components/TextInput”导入TextInput;
从“../components/BackButton”导入BackButton;
从“../components/ProgressDialog”导入ProgressDialog;
从“../core/theme”导入{theme};
从'react redux'导入{connect};
从“../../firebase”导入数据库;
从“反应本机手势处理程序”导入{ScrollView};
类ChatScreen扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
uid:this.props.route.params.id,
姓名:'姓名',
状态:“状态”,
图像:“默认值”,
thumb_图像:“默认值”,
信息:[],
新信息:{
值:“”
},
}
this.currentUserUid=this.props.user.uid;
this.currentUserDoc=db.collection('Users').doc(this.currentUserUid);
this.userDoc=db.collection('Users').doc(this.state.uid);
this.currentUserChatsCollection=this.currentUserDoc.collection('chats');
this.userChatsCollection=this.userDoc.collection('chats');
this.userDoc.onSnapshot(快照=>{
if(snapshot.exists){
snapshot=snapshot.data();
这是我的国家({
name:snapshot.name,
状态:snapshot.status,
image:snapshot.image,
thumb\u image:snapshot.thumb\u image,
});
}
});
this.onSendButtonPressed=this.onSendButtonPressed.bind(this);
}
onSendButtonPressed(){
让message=this.state.new_message.value;
message=message.trim();
log(`[DEBUG]消息:${Message}`);
这是我的国家({
新信息:{
值:“”
}
});
//我在这里清除了文本,然后它就失去了焦点
}
render(){
返回(
{this.props.navigation.goBack()}}/>
//消息将转到此处,但尚未实现
{
这是我的国家({
新消息:{
值:文本
}
});
}}
样式={{
弹性:1,
背景颜色:“浅灰色”,
边界半径:30,
第五名:,
水平方向:15,
填充垂直:5,
大纲:“无”,
}} 
自动资本化
keyboardType='default'
autoCompleteType='off'
textContentType='none'
占位符=“键入消息…”
占位符textcolor='gray'
onKeyPress={(事件)=>{
如果(event.nativeEvent.key=='Enter'){
此.onSendButtonPressed();
}
}}
/>
)
}
}
const styles=StyleSheet.create({
});
常量mapStateToProps=(状态)=>{
const{user}=state.user;
返回{user}
};
导出默认连接(MapStateTops)(聊天屏幕);

查看
.focus()
方法。对它调用
.focus()
需要一个钩子,
钩子
只能在
函数
组件内部调用。请签出