简体   繁体   中英

ReactJS - How to remove whole component , by using child button

I have problem , i want to create TODO app in ReactJS and there is functionality like this:

  1. onClick is showing/hidding AddTaskBox (form in div, where you have to write title and describtion ) - I done it.
  2. In visable AddTaskBox is button with "x" and I want to use him to delete whole "AddTaskBox" - Can't figur it out :(

I'm greeny in React , my thinking about that library may be wrong.

My code:

import React from 'react';
import ReactDOM from 'react-dom';

class AddButton extends React.Component{

  constructor(){
      super();

      this.state = {
      isHidden: false
    }
  }

  toggleHidden () {
      this.setState({
        isHidden: !this.state.isHidden
      })
  }

  render(){
    return(
      <div>
        <div
          onClick={this.toggleHidden.bind(this)}
          className="addtask__btn">
          +
        </div>
        {this.state.isHidden && <AddTaskBox />}
      </div>
    );
  }
}

class AddTaskBox extends React.Component{
  render(){
    return(
      <div className="addtask__box" >
        <button> x </button> // here is my x to close component
        <form>
          <input type="text" placeholder="Nazwa Czynności"/>
          <textarea>
            Opis czynności do wykonania
          </textarea>
          <input className="btn" type="Submit" value="Submit"/>
        </form>
      </div>
    );
  }
}

export {AddButton, AddTaskBox};

Thanks for help :)

Assuming by AddTaskComponent you mean AddTaskBox you would pass the toggleHidden function to AddTaskBox

{this.state.isHidden && <AddTaskBox onClose={this.toggleHidden.bind(this)} />}

and then call the function from the child on click

<button onClick={this.props.onClose}> x </button>

You can pass your toggleHidden() function as prop to AddTasktBox component.

So your close button in AddTaskBox will be like

...
<button onClick={this.props.handleClick}> x </button>
...

You can pass it like

{this.state.isHidden && <AddTaskBox handleClick={this.toggleHidden.bind(this)} />}

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