Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. import React from 'react'
  2. import './App.css'
  3.  
  4.  
  5. class Square extends React.Component {
  6. render() {
  7. const { value, handleClick } = this.props
  8. return (
  9. <button
  10. className="square"
  11. style={{ color: value === 'X' ? 'blue' : 'red' }}
  12. onClick={value ? null : handleClick}
  13. >
  14. {value}
  15. </button>
  16. );
  17. }
  18. }
  19.  
  20. class Board extends React.Component {
  21. constructor(props) {
  22. super(props)
  23. this.state = {
  24. squares: Array(9).fill(null),
  25. turn: 'X'
  26. }
  27. }
  28.  
  29. componentDidMount() {
  30. console.log('mounted')
  31. }
  32.  
  33. componentDidUpdate(prevProps, prevState) {
  34. console.log(prevProps, 'prevProps')
  35. console.log(prevState, 'prevState')
  36. }
  37.  
  38. handleClick = i => {
  39. this.setState(state => ({
  40. squares: [
  41. ...state.squares.slice(0, i),
  42. state.turn,
  43. ...state.squares.slice(i + 1)
  44. ],
  45. turn: state.turn === 'X' ? 'O' : 'X'
  46. }))
  47. }
  48.  
  49. render() {
  50. const status = 'Next player: ' + this.state.turn;
  51.  
  52. return (
  53. <div>
  54. <div className="status">{status}</div>
  55. {[0, 1, 2].map(row => (
  56. <div key={row} className="board-row">
  57. {[0, 1, 2].map((p) => {
  58. const i = row * 3 + p
  59. return (
  60. <Square
  61. key={i}
  62. value={this.state.squares[i]}
  63. handleClick={() => this.handleClick(i)}
  64. />
  65. )
  66. })}
  67. </div>
  68. ))}
  69. </div>
  70. );
  71. }
  72. }
  73.  
  74. class Game extends React.Component {
  75. constructor(props) {
  76. super(props)
  77. this.state = {
  78. started: false
  79. }
  80. }
  81.  
  82. render() {
  83. return (
  84. <div className="game">
  85. <div className="game-board">
  86. {
  87. this.state.started
  88. ? <Board />
  89. : <button onClick={() => this.setState({ started: true })}>
  90. Start
  91. </button>
  92. }
  93. </div>
  94. <div className="game-info">
  95. <div>{/* status */}</div>
  96. <ol>{/* TODO */}</ol>
  97. </div>
  98. </div>
  99. );
  100. }
  101. }
  102.  
  103. export default Game
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement