点击按钮即可自动关闭组件

时间:2018-10-03 08:10:31

标签: javascript reactjs

我有一个react组件,当我单击组件本身上的按钮时,我想自动关闭该组件。

代码如下:

import React from 'react';
import PropTypes from 'prop-types';

const MyReactComponent = (props) => <div>

    <h1>TEST</h1>

    <button onClick={self close here?}>Self Close</button>

</div>

export default MyReactComponent

当我单击按钮时如何获得按钮以关闭组件?

1 个答案:

答案 0 :(得分:3)

那不是React的工作方式。 :-)组件的父代应该向其传递一个用作onClick的属性。响应单击,父组件会更改其状态,以便不再渲染子组件:

const MyReactComponent = (props) => <div>

    <h1>TEST</h1>

    <button onClick={props.onClose}>Self Close</button>

</div>;

class ParentComponent extends React.Component {
  // Note: This uses the class fields proposal, currently at Stage 3 and
  // commonly transpiled in React projects
  closeChild = () => {
    this.setState({
      showChild: false
    });
  };
  constructor(...args) {
    super(...args);
    this.state = {
      showChild: true
    };
  }
  render() {
    return (
      <div>
        {this.state.showChild && <MyReactComponent onClose={this.closeChild} />}
      </div>
    );
  }
}

ReactDOM.render(
  <ParentComponent />,
  document.getElementById("root")
);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

文档"Lifting State Up"部分的更多内容。

相关问题