1. 程式人生 > 其它 >React訓練營:基本元素的使用與狀態管理

React訓練營:基本元素的使用與狀態管理

前置條件

  1. node --version
  2. npm --version
  3. 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中滑鼠跟蹤

  1. 使用狀態
const [mousePostition,setMousePosition] = React.useState({ x:0,y:0});
  1. useEffect
React.useEffect(()=>{
	document.addEventListener('mousemove',handleMouseMove);
},[]);
  1. 滑鼠監聽事件
  function handleMouseMove(event){
    setMousePosition({x:event.pageX, y:event.pageY});
  }
  1. 頁面佈局
<p>
	X :{mousePostition.x},Y:{mousePostition.y}
</p>
  1. 離開頁面時需要取消監聽

  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);