首页 > 解决方案 > 如何将文本区域传递给变量

问题描述

我是新来的反应。我有一个使用 textarea 产生问题的代码。我需要制作一个表格来保存插入到 textarea 中的标题和问题描述。但我似乎没有成功收集文本区域内的内容。这是,你的代码

import React, { Component } from "react";
import "../../styles/styles.css";
import BlockInput from "../pages/blockInput";

class CreateProblem extends Component {
 change = () => {
   
   var text = document.getElementById("title").innerHTML;

   document.getElementById("col1").innerHTML = text;
 };
 changetwo = () => {
  
   var z = document.getElementById("problem").innerHTML;
   document.getElementById("col2").innerHTML = z;
 };

 render() {
   return (
     <div>
     <h3>Enter the problem title : </h3>
           <textarea
               id="title"
               name="textValue"
               onChange={this.handleChange}
               className="item"
             ></textarea>
             <button onClick={this.change}> OK </button>
         
             <h3>Enter the problem description : </h3>
             <div>
               {" "}
               <textarea
                 id="problem"
                 name="textValue"
                 onChange={this.handleChange}
                 className="problemDescribe"
               >
                 {" "}
               </textarea>
               <button onClick={this.changetwo}> OK </button>
             </div>

             <h3> Add new blocks</h3>
             {" "}
             <BlockInput />
             <h4 id="seed">1</h4>
                   
       <table className="table">
         <th>
           <td id="col1"></td>
         </th>
         <th>
           <td>
             <div id="col2"> </div>
           </td>
         </th>
       </table>
     </div>
   );
 }
}

export default CreateProblem;

标签: javascriptreactjs

解决方案


import React, { Component } from "react";
import "./styles.css";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { id: "", problemDesc: "" };
  }
  handleChange = (e) => {
    console.log("problemDesc", e.target.value);
    this.setState({ problemDesc: e.target.value });
  };

  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <textarea onChange={this.handleChange}></textarea>
        <br />
        {this.state.problemDesc} //see the updated value here
      </div>
    );
  }
}

演示:- https://codesandbox.io/s/happy-swartz-wcy2h?file=/src/App.js


推荐阅读