1

使用 React-Native 和有天赋的聊天,我制作了聊天屏幕。但是,我在发送消息时遇到问题。

AS-IS(问题):只要键入消息并选择发送按钮,键盘就会消失并焦点消失。

待办事项:希望在选择发送按钮后保留键盘和焦点输入字段。

这是我的代码

聊天.js

const onSend = messages => {
    const getRoomKey = navigation.getParam("roomKey");
    firebaseService.saveMsg(userData, getRoomKey, messages);
  };

  const renderInputToolBar = () => {
    const props = {
      onSend,
      timeDiffSeconds,
      status
    };

    return <ChatInputBox {...props} />;
  };


  const dateFilter = (previous, current) => {
    const previousDate = moment(previous.createdAt).format(
      "MMMM Do YYYY, h:mm"
    );
    const currentDate = moment(current.createdAt).format("MMMM Do YYYY, h:mm");

    if (previousDate !== currentDate) {
      return current.user.name;
    } else {
      return false;
    }
  };

  const renderAvatar = props => {
    return <Avatar {...props} />;
  };



  const renderBubble = props => {
    const currentMessage = props.currentMessage;
    const previousMessage = props.previousMessage;
    const nextMessage = props.nextMessage;
    console.log(currentMessage);
    if (currentMessage._id == "univel_chat_noti") {

      return (
        <View style={{ justifyContent: "center", alignContent: "center" }}>
          <Text style={{ fontSize: 12, color: "white" }}>
            {currentMessage.text}
          </Text>
        </View>
      );
    } else if (currentMessage.user._id == "univel_chat_leaveroom") {
      return (
        <View style={{ justifyContent: "center", alignContent: "center" }}>
          <Text style={{ fontSize: 12, color: "white" }}>
            {currentMessage.text}
          </Text>
        </View>
      );
    }

    const currentDate = moment(currentMessage.createdAt).format(
      "MMMM Do YYYY, h:mm"
    );
    const previousDate = moment(previousMessage.createdAt).format(
      "MMMM Do YYYY, h:mm"
    );
    const nextDate = moment(nextMessage.createdAt).format("MMMM Do YYYY, h:mm");

    const previousUser = previousMessage.user;
    const currentUser = currentMessage.user;


    if (
      previousDate === currentDate &&
      previousUser &&
      previousUser._id == currentUser._id
    ) {
      props.currentMessage.user.avatar = "is null";
    } else {
      // console.log({
      //   currentDate,
      //   nextDate
      // })
    }

    return (
      <View style={{}}>
        (currentDate !== previousDate ||
          (currentDate == previousDate &&
            previousUser &&
            previousUser._id != currentUser._id)) &&
          userData.nickname !== currentMessage.user.name && (
            <Text style={styles.name}>{currentMessage.user.name}</Text>
          )}
        <Bubble
          textStyle={{
            left: {
              color: "#F7F7F7"
            }
          }}
          wrapperStyle={{
            left: {
              backgroundColor: "#37393B"
            }
          }}
          {...props}
        />
      </View>
    );
  };

  return (
    <View style={styles.container}>
            {
        <GiftedChat
          alwaysShowSend={true}
          textInputProps={{autoFocus: true, blurOnSubmit: false}}
          locale={"kr"}
          messages={msg}
          user={{
            _id: userData._id
          }}
          renderInputToolbar={renderInputToolBar}
          isKeyboardInternallyHandled-={false}
          keyboardShouldPersistTaps="always"
          renderChatEmpty={() => {
            return (
              <StatusAlert
                message={
                  "start"
                }
                image={messageImage}
                imageSetting={{ width: 90, height: 85 }}
                customStyle={{ transform: [{ scaleY: -1 }] }}
              />
            );
          }}
          renderBubble={renderBubble}
          //renderMessage={renderMessage}
          renderChatFooter={() => {
            let hour = Math.floor(timeDiffSeconds / 3600);
            let min = Math.floor((timeDiffSeconds % 3600) / 60);
          }}
          onPressAvatar={user => {
            console.log("click user = ", user);
            setReportPopupState("twoButtonModal");
            setReportTarget(user);
          }}
          showAvatarForEveryMessage={true}
          keyboardShouldPersistTaps="always"
        />      } 

聊天输入框.js

import React, { useState, useRef, useEffect, useCallback } from 'react'
import { View, Text, Item, Input } from 'native-base'
import {
  Platform,
  StyleSheet,
  TouchableOpacity,
  KeyboardAvoidingView,
  TouchableWithoutFeedback,
  Keyboard,
  TextInput
} from "react-native";

const ChatInputBox = ({ onSend, timeDiffSeconds, status }) => {
  const [message, setMessage] = useState('');
  const send = (message) => {
    if (message !== '') {
      onSend(message)
      setMessage('')
    } else {
      return;
    }
  }
  const inputEl = useRef();
  const focusInput = useCallback(() => {
    inputEl.current.focus();
    console.log("checkFocus", inputEl.current)
  }, [])
  useEffect(() => {
    focusInput
    send
    }, []);

  // }else{


    return (
        <View keyboardShouldPersistTaps="always" style={styles.container} opacity={message !== '' ? .8 : .5}>
          <Item rounded style={styles.inputBox}>
            <Input placeholder='Type a message'
                   multiline={true}
                   style={{ textAlignVertical: 'top' }}
                   autoFocus={true}
                   onChangeText={(message) => setMessage(message)}
                   keyboardAppearance={'light'}
                   value={message}
                   ref={inputEl}
                   blurOnSubmit={true}
            />
            <TouchableOpacity style={styles.sendText} onPress={() => send(message) && focusInput} >
              <Text style={message !== '' && { color: '#FFFFFF', fontWeight: 'bold',  paddingLeft: 5, paddingBottom: 5, paddingTop: 5, paddingRight: 5 }}>send</Text>
            </TouchableOpacity>
          </Item>
        </View>
  )

  }


// }

export default ChatInputBox
4

1 回答 1

0

您可以使用“blurOnSubmit”道具来修改 Composer 中的文本输入。

<GiftedChat
  renderComposer={(props) => (
    <Composer
      {...props}
      textInputProps={{
        blurOnSubmit: false, // <---- here
      }}
      multiline={false}
    />
  )}
/>
于 2021-01-06T19:33:27.227 回答