function Box() { const [left, setLeft] = useState(0); const [top, setTop] = useState(0); const [width, setWidth] = useState(100); const [height, setHeight] = useState(100); const handleDragDrop = ({ left, top }) =>{ setLeft(left); setTop(top); } // ... }
function Box() { const [state, setState] = useState({ left: 0, top: 0, width: 100, height: 100 }); const handleDragDrop = ({ left,top }) => { setState({ left, top }); } // ... }
function Box() { const [state, setState] = useState({ left: 0, top: 0, width: 100, height: 100 }); const handleDragDrop = ({ left,top }) =>{ setState({ left, top }); // state => {left, top}, not {left, top, width, height} } // ... }
function Box() { const [state, setState] = useState({ left: 0, top: 0, width: 100, height: 100 }); const handleDragDrop = ({ left,top }) =>{ setState(prevState => {...prevState, left, top}); // } // ... }
function Box() { const [dimensions, setDimensions] = useState({ width: 100, height: 100}); const [position, setPosition] = useState({ left: 0, top: 0 }); const handleDragDrop = ({ left,top }) =>{ setPosition({ left, top }); // } // ... }
props
state
setState
const GreetingMessage({ name, title }) => { return <h3>Greetings {title}. {name}!</h3> }
const EditName = ({ name: oldName, onChange }) => { const [name, setName] = useState(oldName); const handleSubmit = () => { onChange(name); }; const handleChange = (e) => { setName(e.target.value); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={name} onChange={handleChange} /> <button>Save</button> </form> ); };
const EditName = ({ name: oldName, onChange }) => { const [name, setName] = useState(oldName); const handleSubmit = (e) => { e.preventDefault(); // <---- onChange(name); }; const handleChange = (e) => { setName(e.target.value); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={name} onChange={handleChange} /> <button>Save</button> </form> ); };
<h1>
<select />
function App() { const [count, setCount] = React.useState(0); function delayAddOne() { setTimeout(() => { setCount(count + 1); // ??? }, 1000); } return ( <> <h1>Count: {count}</h1> <button onClick={delayAddOne}>+ 1</button> </> ); }
function Counter() { const [count, setCount] = useState(0); const prevCount = /* ?? */; return <h1>Now: {count}, before: {prevCount}</h1>; }
function Counter() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return <h1>Now: {count}, before: {prevCount}</h1>; } function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; }