React:将文本附加到 TextArea

Posted

技术标签:

【中文标题】React:将文本附加到 TextArea【英文标题】:React: Appending Text to a TextArea 【发布时间】:2021-06-01 11:06:12 【问题描述】:

我想问我如何将输出变量(我通过 Axios 的 post 调用获得)附加到 textarea,它以输入变量作为其值。

我真的不知道如何做这样的事情......

我想得到下面视频https://www.youtube.com/watch?v=OcyBYfK6gfY中显示的相同结果

import React from "react";
import  Form, Button  from "react-bootstrap";
import axios from "axios";



import "bootstrap/dist/css/bootstrap.min.css";

const TRANSLATE_API_URL = "/translate";




class Interface extends React.Component 
  constructor(props) 
    super(props);
    this.state = 
      input: "",
      output: "",
      buttonText: "Submit",
      description: "Description",
    ;
    // Bind the event handlers
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);


  





  handleInputChange(e) 
    this.setState( input: e.target.value );
  

  handleClick(e) 
    e.preventDefault();
    let body = 
      prompt: this.state.input
    ;
    axios.post(TRANSLATE_API_URL, body).then(( data:  text  ) => 
      this.setState( output: text );
    );
  

  render() 
    return (
      <div>
        <head />
        <body style= alignItems: "center", justifyContent: "center" >
          <div
            style=
              margin: "auto",
              marginTop: "80px",
              display: "block",
              maxWidth: "500px",
              minWidth: "200px",
              width: "50%"
            
          >
          
            <Form onSubmit=this.handleClick>
              <Form.Group controlId="formBasicEmail">            
                <Form.Label>this.state.description</Form.Label>
                <Form.Control
                  type="text"
                  as="textarea"
                  className="tarea"
                  placeholder="Enter text"
                  value=this.state.input
                  onChange=this.handleInputChange
                ></Form.Control>
              </Form.Group>

              <Button variant="primary" type="submit">
                this.state.buttonText
              </Button>
            </Form>

            this.state.output
            
          </div>
        </body>
      </div>
    );
  


export default Interface;

【问题讨论】:

【参考方案1】:

您只能使用一个 state 属性作为 textarea 值。

要保留之前的文本并添加 Axios 响应,我会尝试:

this.setState( input: this.state.input + text );

代替:

this.setState( output: text );

要创建逐字添加效果,试试这个:

let thisComponent = this;
axios.post(TRANSLATE_API_URL, body).then(( data:  text  ) => 
  
  let wordDelay = 100  // Add a word every 100ms
  
  let timerDelay = 0
  text.split(" ")
    .forEach(word => 
      setTimeout(function()
        thisComponent.setState( input: thisComponent.state.input + " " + word );
      ,timerDelay);
      timerDelay += wordDelay;
    );
);

【讨论】:

非常感谢。还有一件事:我什至想创建视频中显示的文本输入效果。我的一个朋友对我说,我应该尝试,在 axios 响应之后,使用 .split(“”) 拆分文本,这个数组的长度是响应中有多少个单词。然后创建一个 for 循环将循环这个长度,每次迭代都应该将下一个单词添加到变量中,然后设置状态。问题是我不能把它翻译成代码......有什么帮助吗?? 当然...我使用forEach 循环进行了编辑,该循环为每个单词设置了setTimeout 再次感谢。实际上它向我显示了一些错误消息 ')' 预期。预期声明或声明。意外的标记。需要构造函数、方法、访问器或属性。 ';'预计。 很抱歉。我不知道我在回答中这样做“不仅仅是一个错字”。见编辑。 function() 不见了……太奇怪了。我无法解释。【参考方案2】:

这是我收到的错误消息

←→1 of 57 errors on the page
TypeError: Cannot read property 'input' of undefined
(anonymous function)
C:/Users/mario/Desktop/Vs projects/gpt3-sandbox-1/src/components/Interface.js:51
  48 |      let timerDelay = 0;
  49 |      text.split(" ")
  50 |        .forEach(word => setTimeout(function()
> 51 |            this.setState( input: this.state.input + word );
     | ^  52 |          ,timerDelay),
  53 | 

【讨论】:

你能告诉我如何解决它吗? @Louys Patrice Bessette 我明白了...这是因为this 的范围。查看我的编辑,我在其中添加了一个变量以将 this 存储在 thisComponent 中。 很遗憾我没有得到文字输入效果,但是我像以前一样把单词全部输入了,都相互连接 你可以尝试按照有人建议我的 for 循环吗? 该描述很有帮助。我又编辑了。我们越来越近了!【参考方案3】:

我将 Firebase 添加到我的项目中。问题是,现在当我尝试在 textarea 中写一些东西时,我得到 [object Object] 然后出现以下错误

FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: a custom SyntheticEvent object (found in field body)
▶ 11 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.

这是我现在的代码

import React from 'react';
import ReactQuill from 'react-quill';
import debounce from '../helpers';
import BorderColorIcon from '@material-ui/icons/BorderColor';
import  withStyles  from '@material-ui/core/styles';
import styles from './styles';
import axios from "axios";

const TRANSLATE_API_URL = "/translate";


class EditorComponent extends React.Component 
  constructor() 
    super();
    this.state = 
      input: '',
      title: '',
      id: ''
    ;
    this.handleClick = this.handleClick.bind(this);

  

  componentDidMount = () => 
    this.setState(
      input: this.props.selectedNote.body,
      title: this.props.selectedNote.title,
      id: this.props.selectedNote.id
    );
  

  componentDidUpdate = () => 
    if(this.props.selectedNote.id !== this.state.id) 
      this.setState(
        input: this.props.selectedNote.body,
        title: this.props.selectedNote.title,
        id: this.props.selectedNote.id
      );
    
  

  handleClick(e) 
    e.preventDefault();
    

    let body = 
      prompt: this.state.input
    ;
    let thisComponent = this;
    axios.post(TRANSLATE_API_URL, body).then(( data:  text  ) => 
  
  let wordDelay = 100  // Add a word every 100ms
  
  let timerDelay = 0
  text.split(" ")
    .forEach(word => 
      setTimeout(function()
        thisComponent.setState( input: thisComponent.state.input + " " + word );
      ,timerDelay);
      timerDelay += wordDelay;
    );
);
  

  render() 

    const  classes  = this.props;

    return(
      <div className=classes.editorContainer>
        <BorderColorIcon className=classes.editIcon></BorderColorIcon>
        <input
          className=classes.titleInput
          placeholder='Note title...'
          value=this.state.title ? this.state.title : ''
          onChange=(e) => this.updateTitle(e.target.value)>
        </input>

        <form onSubmit=this.handleClick>
        <textarea
          rows=20
          value=this.state.input 
          onChange=this.updateBody>
        </textarea>
        <button type="submit">Ai writer</button>
        </form>
      </div>
    );
  
 

  updateBody = async (val) => 
    await this.setState( input: val );
    this.update();
  ;



  updateTitle = async (txt) => 
    await this.setState( title: txt );
    this.update();
  
  update = debounce(() => 
    this.props.noteUpdate(this.state.id, 
      title: this.state.title,
      body: this.state.input
    )
  , 1500);


export default withStyles(styles)(EditorComponent);

我错过了什么???

【讨论】:

以上是关于React:将文本附加到 TextArea的主要内容,如果未能解决你的问题,请参考以下文章

如何使用钩子将项目附加到 React 组件中的数组?

是否可以将元素添加到 React 的虚拟 DOM 但使用 jQuery 附加到真实 DOM?

将文本附加到类名

React JS 视图未在 setState() 上重新渲染

将文本附加到包含文本的现有字段

如何将其他文本附加到 UIWebView