1.React中的状态
2.React中的语法糖
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; const rootNode = document.getElementById('root'); function App() { //在函数中的状态管理 const [developer, setDeveloper] = React.useState({ name:"", language:"python", yearsExperience:0, isEmployed:false }); React.useEffect(()=>{ document.title = developer.name; },[developer.name]) function handleChangeLanguage(){ setDeveloper({ ...developer, language:"Javascript", yearsExperience:5 }); } function handleChangeYearsExperience(event){ setDeveloper({ ...developer, yearsExperience:event.target.value }) } function handleToggleEmployment(){ setDeveloper((prevState)=>({ ...developer, isEmployed:!developer.isEmployed })) } function handleChangeName(event){ setDeveloper({ ...developer, name:event.target.value }) } return ( <div> <div><button onClick={handleChangeLanguage}>Change Language</button></div> <div><button onClick={handleToggleEmployment}>Change isEmployed</button></div> <div>{developer.language}</div> <div> <input type="number" onChange={handleChangeYearsExperience}></input> <p>I have {developer.yearsExperience} years of experience</p> <p>Employment status:{developer.isEmployed? "Employed":"UnEmployed"}</p> <input type="text" placeholder="change name" onChange={handleChangeName}></input> </div> </div> ) } ReactDOM.render( <div> <App/> </div>, rootNode );
const [mousePostition,setMousePosition] = React.useState({ x:0,y:0});
React.useEffect(()=>{ document.addEventListener('mousemove',handleMouseMove); },[]);
function handleMouseMove(event){ setMousePosition({x:event.pageX, y:event.pageY}); }
<p> X :{mousePostition.x},Y:{mousePostition.y} </p>
React.useEffect(()=>{ document.addEventListener('mousemove',handleMouseMove); return ()=>{ document.removeEventListener('mousemove',handleMouseMove); } },[]);
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; const rootNode = document.getElementById('root'); const baseUrl = 'https://api.github.com/users/'; function App() { const [username,setUsername] = React.useState('rynerisraid') const [user,setUser] = React.useState(null); async function getUser(route){ const response = await fetch(`${baseUrl}${route}`); const data = await response.json(); setUser(data); } React.useEffect(()=>{ getUser(username); },[]); return ( <div> <input type="text" placeholder="Input username" onChange={event=>setUsername(event.target.value)} /> <button onClick={event=>getUser(username)}>Search</button> <button>Clear</button> {user? ( <div> <h2>User:{user.name}</h2> <p>{user.bio}</p> <img alt='avatar' src={user.avatar_url} style={{ height:50 }}></img> </div>) : (<p>Loading</p>)} </div> ) } ReactDOM.render(<App/>,rootNode);