千鋒教育2022版React全家桶教程_react零基礎入門到項目實戰(zhàn)完整版

使用hooks的理由
1、高階組件為了復用,導致代碼層級復雜
2、生命周期復雜
3、寫成functional組件,無狀態(tài)組件,因為需要狀態(tài),又改成class,成本高
useState
引用useState
import React, { useState } from 'react'
創(chuàng)建
const [text, settext] = useState('馬達啦')
input框獲取添加到數組展示
<input style={{ marginTop: 30 }} onChange={(e) => hiderinp(e)} value={text} />
hiderinp事件修改settext值
?const hiderinp = (e) => {
? ? ? ? settext(e.target.value)
? ? }
先創(chuàng)建數組
const [list, setlist] = useState(['哈希喇嘛'])
添加到數組中
<button onClick={hiderbtn}>獲取input值加到list中</button>
const hiderbtn = () => {
? ? ? ? console.log(text);
? ? ? ? setlist([...list, text])
? ? ? ? settext('')
? ? }
刪除數組
<button onClick={() => del(index)}>刪除</button>
const del = (index) => {
? ? ? ? let arr = list
? ? ? ? arr.splice(index, 1)
? ? ? ? setlist([...arr])
? ? }
有數組就不顯示,沒有就展示
<div style={{display:list.length?'none':'block'}}>暫無數據</div>