简体   繁体   中英

React cannot access state

New to react cannot access state. Can someone explain? I am trying to create bar graphs on the board and then whenever the button is clicked I want to perform one iteration of a sorting algorithm. I need the logic for: whenever the button is clicked, then I want to re render the squares based on their heights.Can someone push me in the right direction?

 import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class Square extends React.Component { constructor(props) { super(props); this.state = { value: null, heightSet: 3, }; } render() { var divHeightStyle = { height: this.props.heightSet + 'em', }; return ( <button id={this.props.value} value={this.props.heightSet} style={divHeightStyle} className="square"> {this.props.value} </button> ); } } class Rectangle extends React.Component { constructor(props){ super(props); }; reccheck = () => { this.props.check(); } render(){ return ( <button className="rectangle" onClick={() => this.reccheck()} > </button> ) } } class Board extends React.Component { constructor(props) { super(props); const min = 1; const max = 80; const rand = min + Math.random() * (max - min) const rand1 = min + Math.random() * (max - min) const rand2 = min + Math.random() * (max - min) const rand3 = min + Math.random() * (max - min) this.state = { squares: [rand, rand1, rand2, rand3], }; } renderSquare(i, y) { return <Square value={i} heightSet={y}/>; } check(){ if(this.state.squares[0] > this.state.squares[1]) { alert('0 is bigger'); } } renderRectangle() { return <Rectangle check={this.check}/>; } render() { const status = ''; return ( <div> <div className="status">{status}</div> <div className="board-row"> {this.renderSquare(1,this.state.squares[0])} {this.renderSquare(2,this.state.squares[1])} {this.renderSquare(3,this.state.squares[2])} {this.renderSquare(4,this.state.squares[3])} </div> {this.renderRectangle()} </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> <div>{/* status */}</div> <ol>{/* TODO */}</ol> </div> </div> ); } } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') );

When you call to a function like you are doing, you are using a different this . You should either bind the correct this or use an arrow function.

Binding:

renderRectangle() {
    return <Rectangle check={this.check.bind(this)}/>;
}

or, arrow function:

check: () => {
    if(this.state.squares[0] > this.state.squares[1]) {
        alert('0 is bigger');
}

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