最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React component self close on button click - Stack Overflow

programmeradmin5浏览0评论

I have a react ponent which I want to self close when I click a button that's on the ponent itself.

Here's the code:

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

How can I get the button click to close the ponent when I click it?

I have a react ponent which I want to self close when I click a button that's on the ponent itself.

Here's the code:

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

How can I get the button click to close the ponent when I click it?

Share Improve this question asked Oct 3, 2018 at 8:10 user10450072user10450072 0
Add a ment  | 

1 Answer 1

Reset to default 13

That's not how React works. :-) Instead, the parent of the ponent should pass it a property that it uses as the onClick. In response to the click, the parent ponent changes its state so that the child is no longer rendered:

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
  // monly 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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>

More in the "Lifting State Up" part of the documentation.

发布评论

评论列表(0)

  1. 暂无评论