参考:https://blog.csdn.net/LU_ZHAO/article/details/104999318
函数组件
如果你想写的组件只包含一个 render 方法,并且不包含 state,那么使用函数组件就会更简单。我们不需要定义一个继承于 React.Component 的类,我们可以定义一个函数,这个函数接收 props 作为参数,然后返回需要渲染的元素。函数组件写起来并不像 class 组件那么繁琐,很多组件都可以使用函数组件来写。
把 Square 类替换成下面的函数:
function Square(props) {
return (
<button className="square" onClick={
props.onClick}>
{
props.value}
</button>
);
}
轮流落子
现在井字棋还有一个明显的缺陷有待完善:目前还不能在棋盘上标记 “O”。
我们将 “X” 默认设置为先手棋。你可以通过修改 Board 组件的构造函数中的初始 state 来设置默认的第一步棋子:
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
squares: Array(9).fill(null),
xIsNext: true,
};
}
棋子每移动一步,xIsNext(布尔值)都会反转,该值将确定下一步轮到哪个玩家,并且游戏的状态会被保存下来。我们将通过修改 Board 组件的 handleClick 函数来反转 xIsNext 的值:
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
squares: squares,
xIsNext: !this.state.xIsNext,
});
}
接下来修改 Board 组件 render 方法中 “status” 的值,这样就可以显示下一步是哪个玩家的了