简体   繁体   中英

ReactJS - Updating parent state when child state is changed

I apologize for the lack of working code, but I'm not sure how to go about doing this, so non-working code it is. I am looking to update the this.state.count in the App class when the state of a ToggleBox is altered. I'm sure this has been asked before, thanks in advance.

import React, { Component } from 'react';
import ToggleBox from '../components/ToggleBox';
class App extends Component {
  constructor(props) {
      super(props);
      this.state = {
      total : 60,
      count: 0
    };
  }
  getToggles() {
      let toggles = [];
      for (let i = 0; i < this.state.count; i++) {
        toggles.push(<ToggleBox checked={false} key={i} />);
      }
    return toggles;
  }

  render() {
    let toggles = this.getToggles();
    return (
      <div className="App">
        {{this.state.count}} - {{this.state.total}}
        <div className="container-toggle-box">
            {toggles}
        </div>
      </div>
    );
  }
}

export default App;

...and the component:

import React, {Component} from 'react';
class ToggleBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      active = this.props.checked
    };
    this.handleClick= this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({active: (this.state.active) ? false : true}
  }
  render() {
    let mark = (this.state.active) ? 'x' : 'o'
      return (
        <span>
          {mark}
        </span>
      );
  }
}

export default ToggleBox;

You need to pass ToggleBox a function that updates the count.

For example:

toggles.push(<ToggleBox
    checked={false} 
    key={i}
    incrementCount={() => this.setState({count: this.state.count + 1})}
/>);

Then you just call that method in your child component:

handleClick() {
    this.setState({active: (this.state.active) ? false : true};
    this.props.incrementCount();
}

This pattern is often referred to as "Flux" (or, to be more accurate, it's a piece of the overall Flux pattern), and it's a core part of how React was designed to be used. By passing the function in in this way your child component doesn't have to know anything about how count works or how it's incremented. This makes things easy for the child, but more importantly it makes it a lot easier when you want to change how the count works, because there's only a single place (the parent component) which controls it.

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