简体   繁体   中英

Changing state of a different component - ReactJS

I am trying to build a simple app using react that has two components, one embedded in the other. The child component is a contracted menu and when it is clicked, it expands. I want to be able to re-contract it when the parent element is clicked, or when the child element looses focus.

This is what the parent component looks like:

import React from 'react';
import MenuBar from './_components/MenuBar.js';

var div = React.createFactory('div');
var menu = React.createFactory(MenuBar);

var HomeComponent = React.createClass({
    render: function() {
        return div({ className: 'page home current', onClick: changeChildState //change the state of the child component to false },
            menu()
        )
    }
});



export default HomeComponent;

This is what the child component looks like:

import React from 'react';

var div = React.createFactory('div');

var MenuBar = React.createClass({
    getInitialState: function() {
        return ({menuIsShowing: false});
    }
    showMenu: function() {
        return this.setState({menuIsShowing: true});
    },
    render: function() {
        var isShowing = this.state.menuIsShowing ? 'menuSlideDown' : '';
        return div({ className: 'menu-bar ' + isShowing, onClick: this.showMenu });
    }
});

export default MenuBar;

I am unsure of the correct way of doing this in react and would love some input.

One way to achieve you goal is to hold the ChildComponent expand status in the parent component status. Pass the isExpand boolean to the child component by props. At the same time, also pass a callback to the ChildComponent to update the parent isExpand status.

var HomeComponent = React.createClass({
  getInitialState: function() {
    return ({menuIsShowing: false});
  },

  changeChildOpenStatus: function() {
    this.setState({menuIsShowing: true});
  },

  render: function() {
    return div({ className: 'page home current', onClick: this.changeChildOpenStatus },
      menu({ menuIsShowing: this.state.menuIsShowing, handleChildClicked: this.changeChildOpenStatus })
    )
  }
});

Then in the child component

var MenuBar = React.createClass({
  handleExpandClicked: function(event) {
    this.props.handleChildClicked(event);
  },

  render: function() {
    var isShowing = this.props.menuIsShowing;
    return div({ className: 'menu-bar ' + isShowing, onClick: this.handleExpandClicked });
  }

});

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