求助:初学react
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Square(props) {
return (
<div className='square' onClick={props.onClick}>
<div className={props.value === 2 ? 'black' : ''}></div>
<div className={props.value === 1 ? 'white' : ''}></div>
</div>
);
}
class Board extends React.Component {
renderSquare() {
let table = [];
for (let i = 0; i < this.props.row; i++) {
let rowList = [];
for (let j = 0; j < this.props.col; j++) {
rowList.push(<Square value={this.props.value.length>0?this.props.value[i][j]:''} key={j} onClick={() => this.props.onClick(i, j)} />)
}
table.push(<div className="board-row" key={i}>{rowList}</div>)
}
console.log(table)
return table
}
render() {
return (
<div> {this.renderSquare()}</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [
{ value: [] }
],
stepNumber: 0,//历史序列号
row: 3,//行
col: 3,//列
};
this.rowChange = this.rowChange.bind(this);
this.colChange = this.colChange.bind(this);
}
componentDidMount() {
this.setData()
}
setData() {
const history = this.state.history
let row = this.state.row
let col = this.state.col
history.map((item, key) => {
if (key === this.state.stepNumber) {
let List = []
for (let i = 0; i < row; i++) {
let list = []
for (let j = 0; j < col; j++) {
list.push(null)
}
List.push(list)
}
item.value = List
}
return item
})
this.setState({ history })
}
rowChange(e) {
let row = e.target.value
this.setState({row:row},()=>{
this.setData()
})
}
colChange(e) {
let col = e.target.value
this.setState({col},()=>{
this.setData()
})
}
createDots(row,col){
const history = this.state.history.slice(0, this.state.stepNumber + 1)
const copyHistory = JSON.parse(JSON.stringify(history[this.state.stepNumber]));
const value = copyHistory.value;
if (value[row][col]) return
value[row][col] = this.state.xIsNext ? 1 : 2;
this.setState({
history: history.concat(copyHistory),
stepNumber: history.length,
});
}
render() {
let row = this.state.row
let col = this.state.col
const history = this.state.history;
const value = history[this.state.stepNumber].value;
return (
<div>
<div className="setTable">
<div>行<input type="text" value={row} onChange={this.rowChange}></input></div>
<div>列<input type="text" value={col} onChange={this.colChange}></input></div>
</div>
<div className="game">
<div className="game-board">
<Board value={value} row={row} col={col} onClick={(row,col)=>{this.createDots(row,col)}}/>
</div>
<div className="game-info"></div>
</div>
</div>
);
}
}
ReactDOM.render(<Game />, document.getElementById("root"));
现在是棋格与值绑定有些问题,两个input控制棋格,当行输入十或者以上,控制台会报Cannot read property '0' of undefined,也就是二维数组里没有这项,这是为啥?有啥解决方案么?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…