尚硅谷2021版React技术全家桶全套完整版(零基础入门到精通/男神天禹老师亲授)
在看了老师的讲解后,自己打了一遍,以下总结了一下老师说的注意点和自己编写代码时注意点,后面附上自己写的代码。
流程
1. 创建项目并启动
-
全局安装
npm i/yarn -g create-react-app
-
创建项目
create-react-app 项目名称
-
启动项目
npm start/yarn start
2. 拆分组件、实现静态组件
原生HTML转化为ReacDom时注意以下问题:
- 替换 class= 为 className=
- 替换style = “…” 为 { {…}} 且注意内部引号问题
- 标签闭和" / ",尤其是input、br
3.实现动态组件
-
组件存放位置
【单个】组件使用:放在其自身的state中
【多个】组件使用:放在共同的父组件state中(状态提升) -
状态在哪里,操作状态的方法就在哪里
-
父子通信:
【父】→【子】:通过props传递
【子】→【父】:通过props传递,在子组件中定义函数并将数据作为参数传递出去 -
自动生成唯一标识符id:nanoid,详情请看https://github.com/ai/nanoid
-
注意defaultChecked 和 checked的区别,类似的还有:defaultValue 和 value
App.jsx
import React, {
Component } from 'react'
import Header from './components/Header'
import List from './components/List'
import Footer from './components/Footer'
import './App.css'
export default class App extends Component {
//初始化状态
state = {
todos: [
{
id: '001', name: '吃饭', done: true },
{
id: '002', name: '睡觉', done: true },
{
id: '003', name: '打代码', done: false },
{
id: '004', name: '逛街', done: false }
]
}
addTodoObj = (newObj) => {
const {
todos } = this.state
const newTodos = [newObj, ...todos]
this.setState({
todos: newTodos })
}
updateTodos = (id) => {
console.log(id)
this.setState({
todos: this.state.todos.map(item => {
return item.id === id ? {
...item, done: !item.done } : item
})
})
}