简体   繁体   中英

pushing content of textarea into an array

I have a textarea and i want to push its content into an array that I defined

I have created a Tasks component and used the onClick property to push the value of its textarea's innerhtml into the array.

App.js :

import React from 'react';
import Tasks from './tasks.js';
import './App.css';

let tasks= [
  {name:""},
  {name:""},
  {name:""},
  {name:""},
  {name:""}

]

function App(props) {
  return (
    <div className="App">
      <Tasks onClick={()=>{

        tasks.push(this.props.value)
      }} />
     </div>
  );
}

export default App;

tasks.js:

import React from 'react'



class Tasks extends React.Component {
    render() {
        return (<div>
<textarea value={this.props.value} ></textarea>
<button onClick={this.props.onClick}>Add task</button>
        </div>)

    }

}



export default Tasks

The app compiled successfully, but when I click on the button, the "Cannot read property 'props' of undefined" error appears

Maintain state in child component to store value of text-area,

constructor(props) {
    super(props)
    this.state = {
      value: '',
    }
  }

You can set state value, when your text-area change,

handleChange = e => {
    this.setState({value: e.target.value})
}

On the click of the button, you need to pass the value from text-area to parent component like,

<textarea value={this.state.value} onChange={this.handleChange} />
<button onClick={() => this.props.onClick(this.state.value)}>
     Add task
</button>

In parent component, you can push value of text-area into your array.

function addData(val) {
  tasks.push(val)
  console.log(tasks)
}
<Tasks onClick={value => addData(value)} />

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM