首页 > 其他 > 详细

useState 使用方法

时间:2021-08-20 21:42:36      阅读:33      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

import React,{useState} from ‘react‘ 
export default function ComplexHookState() { 
    const [friends, setFriends] = useState([‘李雷‘,‘科比‘]) 
    const [students, setStudents] = useState([
        { id:110, name:‘Eric‘,  age:28 },
        { id:111, name:‘kebo‘,  age:22 },
        { id:112, name:‘lily‘,  age:25 }
    ]) 
    function incrementAgeWithIndex(index){ 
        const newStudents = [...students]
        newStudents[index].age += 1 
        setStudents(newStudents)
    } 
    return (
        <div> 
            <h2>好友列表</h2>
            <ul>
                { friends.map((item,index)=>{ return <li key={index}>{item}</li> }) }  
                <button onClick={e => setFriends([...friends,‘tom‘])}>添加朋友</button>
            </ul> 
            <h2>学生列表</h2>
            <ul>
                { students.map((item,index)=>{
                        return ( <li key={index}> <span>名字:{item.name} 年龄:{item.age}</span> 
                               <button onClick={e=> incrementAgeWithIndex(index)}>age+1</button> </li> )
                }) }   
            </ul>

        </div>
    )
}
 
技术分享图片

 

 

import React ,{useState} from ‘react‘

export default function CounterHock() {
    
    const arr = useState(0);
    console.log(arr);
    const state = arr[0];
    const setState = arr[1];
    return (
        <div>
             <h2>当前计数: {state}</h2>
            <button onClick={e=> setState(state + 1 )} > +1 </button>
            <button onClick={e=> setState(state - 1 )} > -1 </button>
        </div>
    )
}

 

useState 使用方法

原文:https://www.cnblogs.com/eric-share/p/15167531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!