带钩的ReactJS / Chatbot [英] ReactJS / Chatbot with hooks

查看:70
本文介绍了带钩的ReactJS / Chatbot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态聊天机器人,可以在其中显示消息:

I have a static chatbot where I can display the messages through this:


< ChatMessage bot = {true}>嗨。< / ChatMessage>

像这样的img:

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>
  );
};

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

But I would like to know how I could make it dynamic to display a message accordingly with what is typed in the text area and as a result call some function to check what was typed as a string and return a response. But I don't know how to resolve this situation. Basically I need to display a message typed by a user in the chat and send that message to my back-end (or some function of the front-end), then that function will send me a response.

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

推荐答案

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

In that case you've to keep your messages array in a state variable and add your messages dynamically on press of a button. You can do something like:

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>
    </>
  )
}

这只是一个例子,您可以将其映射到用例上。

It's only an example, you can map it on your use case.

这篇关于带钩的ReactJS / Chatbot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆