score:1

Accepted answer

that's because passing this.getstatus directly to child component will lose its caller (this). instead, you can pass a 'wrapped version' of it.

this closure will preserve caller of getstatus, thus return correct value.

function square(props) {
  return (
    <button classname="square"> {props.value} </button>
  );
}

class board extends react.component {

  rendersquare(i) {
    return <square />;
  }

  render() {
    return (
      <div classname="status">{this.props.printstatus()}</div>
    );
  }
}

class game extends react.component {

// constructor
constructor(props) {
  super(props);
  this.state = {
    myprop: 'hi'
  }
}

// gets gameplay status
getstatus() {

  return this.state.myprop;
}

  render() {
    return (
      <div classname="game">
        <div classname="game-board">
          <board printstatus={() =>  this.getstatus()}/>
        </div>
      </div>
    );
  }
}

const rootelement = document.getelementbyid("root");
reactdom.render(
    <game />,
  rootelement
);
<div id="root">
     
</div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

score:0

or you can just define getstatus as an arrow function:

getstatus = () => this.state.myprop

check this out: https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480

score:1

you need to bind this to the getstatus function in your constructor.

constructor(props) {
  super(props);
  this.state = {
    myprop: 'hi'
  };
  this.getstatus = this.getstatus.bind(this);
}

https://gist.github.com/fongandrew/f28245920a41788e084d77877e65f22f


Related Query

More Query from same tag