如何在reactjs中“通过单击删除按钮删除文本区域”

时间:2020-11-05 11:02:28

标签: reactjs

  • 我想在reactjs中执行删除操作
  • 我有一个文本区域和删除按钮
  • 如果我单击删除按钮,则应该删除文本区域
  • 在不使用索引的情况下如何对单个文本区域执行此操作。
  • 代码:

import React,{Component} from "react";
import ReactDOM from "react-dom";
class App extends Component {
  handleRemove(){

  }
 render()
 {
return(
 
  <div className="row"> 
  <div className="left">
 
<button>Edit</button>
 </div>
 <div className="container1">
 <input
 className="textstyle"  
  // onChange={(e)=>this.handleChange()} 
  
   /> 
   <button onClick={()=>this.handleRemove()}>Delete</button> 
   </div>
   
</div> )
 }
  
  //onclick add a textarea
  
   
  
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>

1 个答案:

答案 0 :(得分:0)

您可以为textArea元素设置状态,然后在删除时将其从屏幕上删除。

像这样:


import React,{Component} from "react";
import ReactDOM from "react-dom";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {textAreas: ['textAreaID']};
  }

  handleRemove(index){
    this.setState({
        textAreas: this.state.textAreas.splic(index, 1);
    })

  }

  handleCreate(){
   this.setState({
        textAreas: this.state.textAreas.push('newID');
})
}
 render()
 {
return(
 
  <div className="row"> 
  <div className="left"

<button>Edit</button>
 </div>
{this.state.textAreas.lenght > 0 ? 
 this.state.textAreas.map((textAreas, index) => <div className="container1">
     <input className="textstyle" onChange={(e)=>this.handleChange()}/> ) 
     <button onClick={(e)=>this.handleRemove(index)}>Delete</button> 
   </div>
: ''})}
  
  //onclick add a textarea
  <button onClick={(e)=>this.handleCreate()}>Create Text Area</button> 
   
  
}
export default App;