Zak Chen
Zak Chen

Reputation: 81

React.js using Parent's function to control Child's state

I want to use parent's function to control child's state

so I code these in my parent.jsx

changeFilter(){
if(this.state.imgFilter=='none'){
  this.setState({
    imgFilter:'imgFilter',dataFilter:1
  },()=>this.selectFood)
}
else if(this.state.imgFilter=='imgFilter'){
  this.setState({
    imgFilter:'none',dataFilter:0
  },()=>this.selectFood)
}

}

but I want to let this in parent.jsx be this in child.js

how could I do that?

Upvotes: 1

Views: 606

Answers (1)

Emperor_Earth
Emperor_Earth

Reputation: 71

The parent component

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child filter={this.state.imgFilter} toggleFilter={this._toggleFilter} />
      </div>
    )
  }

  constructor() {
    super()

    this.state = {
      imgFilter: "none",
    }

    this._toggleFilter = this._toggleFilter.bind(this)
  }

  _toggleFilter() {
    this.setState(state => {
      return {
        imgFilter: state.imgFilter === "imgFilter" ? "none" : "imgFilter",
      }      
    })
  }
}

Notes

  • line 1: Change Parent to your parent's component name

  • line 2: Stylistic to put render() first. Most put constructor() first

  • line 5: highly recommend caching your functions rather than inlining them into your render function. this avoids recreating the function on re-renders

  • line 10-11: only need props in constructor()/super() if using inside the constructor()

  • line 17: binding your function's this

  • line 20: js convention to put underscore in front of method/function that's local

  • line 21: recommend functional setState(). stricter ordering of state mutations to aid reproducibility. object-style setState(), the default, is async and can update state out of order

  • line 23: convention prefers having "none" as the fallback clause, ordering the ternary this way to keep in line with your original post

The child component

class Child extends React.Component {
  render() {
    // imgFilter && toggleFilter() are accessible from this.props
    // this.props.imgFilter
    // this.props.toggleFilter()
    // e.g. <div onClick={this.props.toggleFilter()}></div>

    return <div></div>
  }
}

Upvotes: 1

Related Questions