簡體   English   中英

React 無法訪問狀態

[英]React cannot access state

新來的反應無法訪問狀態。 有人可以解釋一下嗎? 我正在嘗試在板上創建條形圖,然后每當單擊按鈕時,我都想執行排序算法的一次迭代。 我需要以下邏輯:每當單擊按鈕時,我想根據它們的高度重新渲染正方形。有人可以將我推向正確的方向嗎?

 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') );

當您調用一個函數時,您正在使用不同的this 您應該綁定正確的 this 或使用箭頭函數。

捆綁:

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

或者,箭頭函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM