Сделали колбэк с кнопками и именами

This commit is contained in:
2026-05-05 21:10:47 +03:00
parent 1bc2e883a1
commit 3d34262203
+13 -8
View File
@@ -1,21 +1,26 @@
import styles from './styles/App.module.scss' import styles from './styles/App.module.scss'
import React, { useState } from 'react' import React, { useState, useCallback } from 'react'
function Parent() { function Parent() {
const [count,setCount] = useState(0); const names = ['Alex','Bob','Deniel'];
//const handleCallback = () => setCount(count + 1) const handleNameClick = useCallback( name => {
const increment = React.useCallback(() => setCount(count + 1)); alert(`Вы нажали на ${name}`);
},[]);
return ( return (
<> <>
<div>{count}</div> <h2>Проверка React.useCallback</h2>
<Child onClick={increment} /> {names.map(name => (
<Child key={name} name={name} onClick={handleNameClick} />
))}
</> </>
); );
} }
const Child = React.memo(({ onClick }) => { const Child = React.memo(({ name, onClick }) => {
console.log('child rendered'); console.log('child rendered');
return <button onClick={onClick}>Нажми меня</button> const handleClick = useCallback(()=>onClick(name),[name, onClick]);
return <button onClick={handleClick}>{name}</button>
}) })
function App() { function App() {