【问题标题】:ReactJS / Chatbot with hooksReactJS / 带有钩子的聊天机器人
【发布时间】:2020-05-16 11:14:17
【问题描述】:

我有一个静态聊天机器人,我可以通过它显示消息:

<ChatMessage bot={true}>Hi.</ChatMessage>

喜欢这张图片:

const ChatBot = () => {
  return (
    <Styled.ChatBox>
      <ChatMessage bot={true}>Hi.</ChatMessage>
      <ChatMessage bot={false}>Hello.</ChatMessage>
    </Styled.ChatBox>
  );
};

这是我的聊天机器人:

function ChatMessage(props) {
  return (
    <Styled.ChatMessage bot={props.bot}>{props.children}</Styled.ChatMessage>
  );
}

ChatMessage.defaultProps = {
  bot: false,
};

const Chat = props => {
  console.log(props.children);
  return (
    <Styled.ChatBox>
      <Styled.ChatHeader />
      <Styled.ChatLog>{props.children}</Styled.ChatLog>
      <Styled.ChatInput>
        <textarea placeholder="aaaaa ..." rows={4} />
        <button>Send</button>
      </Styled.ChatInput>
    </Styled.ChatBox>
  );
};

但我想知道如何使动态显示消息与在文本区域中键入的内容相应地显示消息,并因此调用一些函数来检查作为字符串键入的内容并返回响应。但我不知道如何解决这种情况。基本上我需要在聊天中显示用户输入的消息并将该消息发送到我的后端(或前端的某些功能),然后该功能将向我发送响应。

例如:https://codesandbox.io/s/eager-torvalds-fyi77

【问题讨论】:

    标签: javascript reactjs chatbot


    【解决方案1】:

    在这种情况下,您必须将消息数组保存在状态变量中,并在按下按钮时动态添加消息。您可以执行以下操作:

    import React, { useState } from 'react'
    
    const YourComponent = () => {
      const [messages, setMessages] = useState([])
      const [text, setText] = useState('')
    
      const handleClick = () => {
        setMessages(prevMessages => [...prevMessages, text]);
        setText('')
      }
    
      return (
        <>
          <textarea onChange={e => setText(e.target.value)}>{text}</textarea>
          <button onClick={handleClick}>Submit</button>
        </>
      )
    }
    

    这只是一个示例,您可以将其映射到您的用例中。

    【讨论】:

    • 你好朋友,谢谢你认为最好的选择是使用 redux 来存储这些消息吗?因为我会将它们发送到后端并且我会收到响应吗?
    • 我理解这部分,但我不确定我将如何做这部分: const ChatBot = () => { return ( 嗨。 你好。 ); };
    • 我试过了,效果不是很好我的组件日志中没有出现文本
    【解决方案2】:
    <Chat>
      <ChatMessage bot={true}>Hi.</ChatMessage>
      <ChatMessage bot={false}>Hello.</ChatMessage>
    </Chat>
    

    首先,上面的代码应该改成使用prop而不是硬编码,像这样:

    const ChatBot = ({ messages }) => {
      return (
        <Chat>
          {messages.map(message => <ChatMessage bot={message.fromBot}>{message.text}</ChatMessage>)}
        </Chat>
      );
    };
    

    其次,在你的父级中,你应该将connect你的messages状态转换为redux(或者干脆在组件中加载消息并将其保存在messages状态),并将其作为道具传递给上述组件.

    最后,一旦你提交了一条新消息,你就可以调用一个从父级传递过来的sendMessage prop,它调用API 来发送消息。此外,您需要记住在成功将消息发送到服务器后更新当前的消息列表,以便您的本地状态是最新的。

    【讨论】:

    • 哎呀,我喜欢这个解决方案,你能给我一个例子,说明我会如何和爸爸一起做吗?基本上是一个按钮并使用 useState 保存消息,但我如何将它发送到我的组件聊天?
    • 将其作为道具发送,如下所示:
    • 我无法想象如何使用 chat.js 和 index.js 以及钩子来做到这一点,我有点困惑。你能以你父亲为榜样吗?
    猜你喜欢
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 2022-01-04
    相关资源
    最近更新 更多