React训练营:基本元素的使用与状态管理
前置条件
- node --version
- npm --version
- npx create-react-app react-project
入门样例
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
);
React中鼠标跟踪
- 使用状态
const [mousePostition,setMousePosition] = React.useState({ x:0,y:0});
- useEffect
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);
}
},[]);
Demo获取Github 中的个人信息
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);