React 入门小例子

 1 class Square extends React.Component {
 2   constructor(props) {
 3     super(props);
 4     this.state = {
 5       value: null,
 6     };
 7   }
 8 
 9   render() {
10     return (
11       <button
12         className="square"
13         onClick={() => this.setState({value: 'X'})}
14       >
15         {this.state.value}
16       </button>
17     );
18   }
19 }
20 
21 class Board extends React.Component {
22   renderSquare(i) {
23     return <Square />;
24   }
25 
26   render() {
27     const status = 'Next player: X';
28 
29     return (
30       <div>
31         <div className="status">{status}</div>
32         <div className="board-row">
33           {this.renderSquare(0)}
34           {this.renderSquare(1)}
35           {this.renderSquare(2)}
36         </div>
37         <div className="board-row">
38           {this.renderSquare(3)}
39           {this.renderSquare(4)}
40           {this.renderSquare(5)}
41         </div>
42         <div className="board-row">
43           {this.renderSquare(6)}
44           {this.renderSquare(7)}
45           {this.renderSquare(8)}
46         </div>
47       </div>
48     );
49   }
50 }
51 
52 class Game extends React.Component {
53   render() {
54     return (
55       <div className="game">
56         <div className="game-board">
57           <Board />
58         </div>
59         <div className="game-info">
60           <div>{/* status */}</div>
61           <ol>{/* TODO */}</ol>
62         </div>
63       </div>
64     );
65   }
66 }
67 
68 // ========================================
69 
70 ReactDOM.render(
71   <Game />,
72   document.getElementById('root')
73 );

 

上一篇:React的小结


下一篇:手把手教你在 Vue 中使用 JSX,不怕学不会!【建议收藏】