React: Happy react Note
Tags: react, udemy-react
Add env
-
https://create-react-app.dev/docs/adding-custom-environment-variables/
- 一定要 REACT_APP_ 開頭喔
functional components redirect [history]
-
-
import { useHistory } from "react-router-dom"; function BackButton({ children }) { let history = useHistory() return ( <button type="button" onClick={() => history.goBack()}> {children} </button> ) }
-
好棒棒網站 分享 functional components and class components
Using Hooks in input fields
import React, { useState } from 'react'
export const ControlledComponentWithHooks = () => {
const [input, setInput] = useState({})
const handleInputChange = (e) => setInput({
...input,
[e.currentTarget.name]: e.currentTarget.value
})
return (
<form>
<div>
<label>Username:</label>
<input type="text" name="username" onChange={handleInputChange} />
</div>
<div>
<label>Password:</label>
<input type="text" name="password" onChange={handleInputChange} />
</div>
<input type="submit" />
</form>
)
}
- 抽出來
import { useState } from 'react'
export const useInputChange = () => {
const [input, setInput] = useState({})
const handleInputChange = (e) => setInput({
...input,
[e.currentTarget.name]: e.currentTarget.value
})
return [input, handleInputChange]
}
import React from 'react'
import { useInputChange } from './useInputChange'
export const ControlledComponentWithHooks = () => {
const [input, handleInputChange] = useInputChange()
return (
<form>
<div>
<label>Username:</label>
<input type="text" name="username" onChange={handleInputChange} />
</div>
<div>
<label>Password:</label>
<input type="text" name="password" onChange={handleInputChange} />
</div>
<input type="submit" />
</form>
)
}