react + 图灵api 实现模拟客服
1.代码
chatbot/index.tsx
/** * 客服 */ import React, { useState, useRef } from 'react'; import { Button, Toast, InputItem } from 'antd-mobile'; import { RobotUrl, ApiKeys } from 'utils/constants'; import askImg from 'Images/user_center/ask.jpg'; import answerImg from 'Images/user_center/answer.jpg'; import './index.less'; interface IProps { } function ChatBot(props: IProps) { const [apiKey, setApiKey] = useState<string>(ApiKeys[0]); const [message, setMessage] = useState<string>(''); const [askList, setAskList] = useState<string[]>([]); const [answerList, setAnswerList] = useState<string[]>([]); const listRef: any = useRef(null); function sendMessage() { if (!message) { Toast.info('不能发送空白消息哦'); return; } setAskList([...askList, message]); // 请求图灵接口 fetch(`${RobotUrl}?key=${apiKey}&info=${message}`, { method: 'POST', // type: 'cors' }).then(function (response: any) { return response.json() }).then(function (detail: any) { setAnswerList([...answerList, detail.text]); listRef.current.scrollTop = listRef.current.scrollHeight; if (+detail.code !== 100000) setApiKey(ApiKeys[1]); }).finally(() => setMessage('')) } return ( <div className="chatbot_content"> <div className="message_list" ref={listRef}> {askList.map((elem, index) => ( <div className="container" key={index}> <div className="ask_content"> <p className="message">{elem}</p> <img src={askImg} className="avatar" /> </div> <div className="answer_content"> <img src={answerImg} className="avatar" /> <p className="message">{answerList[index]}</p> </div> </div> ))} </div> <div className="send_message"> <InputItem className="send_txt" placeholder="请输入" value={message} onChange={(msg: string) => setMessage(msg)} /> <Button type="primary" size="small" inline onClick={sendMessage} className="send_btn" >发送</Button> </div> </div> ); } export default ChatBot;
2.效果图