新的无法访问状态。有人可以解释吗? 我试图在板上创建条形图,然后每当单击按钮时,我都希望执行一次排序算法迭代。我需要逻辑:每当单击按钮时,我都希望根据其高度重新渲染正方形。有人可以向正确的方向推动我吗?
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')
);
答案 0 :(得分:0)
在调用函数时,您正在使用其他this
。您应该绑定正确的this或使用箭头功能。
绑定:
renderRectangle() {
return <Rectangle check={this.check.bind(this)}/>;
}
或箭头功能:
check: () => {
if(this.state.squares[0] > this.state.squares[1]) {
alert('0 is bigger');
}