删除组件onClick in react

时间:2017-02-14 08:32:33

标签: reactjs

点击某个overlay时,我正在显示input页面。现在,我希望在overlay中某位用户clicks时删除该overlay页面。我怎么能这样做?

我正在点击这样显示叠加

constructor(props) {
        super(props);

        this.state = {
            showComponent: false,
        };
        this.popup_ques = this.popup_ques.bind(this);

    }

    popup_ques() {
        this.setState({
            showComponent: true,
        });
    }

 render() {
        return (
            <div className="ff">
                <div className="middle_div">
                    <input className='post_data_input' placeholder="Ask your question here" ref="postTxt" onClick={this.popup_ques}/>
                </div>

                {this.state.showComponent ? <QuestionOverlay/> : null}

            </div>
        );
    }

我的overlay位于组件QuestionOverlay

class QuestionOverlay extends Component {
    constructor() {
        super();
    }

    closeOverLay = (e) => {
        alert("fse");
    }

    render() {
        return (
            //Here I have implemented my overlay
        )
    }

}

export default QuestionOverlay; 

那么当我点击叠加层上的某个地方时,如何关闭/删除叠加组件呢?

1 个答案:

答案 0 :(得分:1)

从Overlay的父组件(显示Overlay的组件)中传递一个函数,该组件在Overlay中称为onClick。此函数会将父级this.state.showComponent更新为false以隐藏叠加层。

<强>父

constructor(props) {
    super(props);

    this.state = {
        showComponent: false,
    };
    this.popup_ques = this.popup_ques.bind(this);
    this.hide_overlay = this.hide_overlay.bind(this);

}

popup_ques() {
    this.setState({
        showComponent: true,
    });
}

hide_overlay() {
  this.setState({
    showComponent: false
  })
}

render() {
    return (
        <div className="ff">
            <div className="middle_div">
                <input className='post_data_input' placeholder="Ask your question here" ref="postTxt" onClick={this.popup_ques}/>
            </div>

            {this.state.showComponent && <QuestionOverlay hideOverlay={this.hide_overlay} />}

        </div>
    );
}

<强>重叠

class QuestionOverlay extends Component {
  constructor() {
    super();
  }

  closeOverLay = (e) => {
    alert("fse");
  }

  render() {
    return (
        <div onClick={this.props.hideOverlay}>
          // Overlay content
        </div>
    )
  }

}

export default QuestionOverlay;