react第6天
2022-11-23 本文已影响0人
怎么昵称
记住组件的数据
useState
import { useState } from 'react'
初始化数据
const [index, setIndex] = useState(0)
// index 初始值为0
//setIndex 可以更改index 值
在事件中触发
function handleClick (){
setIndex(index + 1)
}
<button onClick={handleClick}>
Next
</button>
触发渲染render
有两种情况:
组件初始化render
组件中的数据被更新重新render
createRoot 让你创建的节点在浏览器节点中展示组件
import {createRoot} from 'react-dom/client'
import Image from './Image.js'
const root = createRoot(document.getElementById('root'))
root.render(<Image />)
图片函数组件Image.js
export defult function Image(){
return (
<img
src= "http://dee.jpg"
alt = "jpg"
/>
)
}
实现的效果就是 输入框可以输入文本
点击按钮触发显示your message is on its way
import {useState} from 'react'
export default function Form(){
const [isSent, setIsSent ] = useState(false)
const [message, setMessage] = useState(false)
//判断当前值 是否显示dom
if(isSent){
return <h1>your message is on its way </h1>
}
return (
<form onSubmit = {
(e)=> {
e.preventDefault()
setIsSent(true)
sendMessage(message)
}
}>
<textarea placeholder="message" value = {message} onChange= {e=> setMessage(e.target.value )}>
</textarea>
<button type = "submit">Send</button>
</form>
)
}
function sendMessage(message) {
// ...
}
count 值
点击触发三次方法执行
明明执行三次 但是 结果还是每次都加 1
import {useState} from 'react'
export default function Counter(){
const [] = useState(0)
return (
<>
<h1>{number}</h1>
<button
onCllick = {
()=>{
setNumber(number + 1)
setNumber(number + 1)
setNumber(number + 1)
}
}
>
+ 3
</button>
</>
)
}
因为每次number 每次都是0 执行了三遍后 number+ 1 还是1