写在前面:
磨磨唧唧了好久终于下定决心开始学react,刚刚接触感觉有点无从下脚...新的语法新的格式跟vue就像两种物种...倒是很好奇路由和store是怎么实现的了~v~,一点一点来吧!!!
(一)创建项目
使用vite创建
npm create vite
选择react项目,欧啦现在开始:
main.tsx文件:
还是熟悉的味道,鉴于我还搞不清楚组件和路由,就直接在app.tsx里面开干
(二)制作井字棋游戏
1. 搭建九宫格形状
(1)用Square组件实现小格子
function Square() {
return (
<>
<button className='square'>x</button>
</>
)
}
(2)使用数组map方法渲染出九个Square组件
不同于vue的v-for,react使用数组方法实现列表的渲染
function Board() {
// 存储每个格子的值 初始化为空
const squares = new Array(9).fill('')
const listSquare = squares.map((value, index) => (
<Square key={index} />
))
return (
<>
{listSquare}
</>
)
}
(3)通过props传递数据
将square组件的值存储在Board里面,通过props传值
function Square({ content }) {
return (
<>
<button className='square'>{content}</button>
</>
)
}
function Board() {
...
const listSquare = squares.map((value, index) => (
<Square key={index} content={value} />
))
...
}