Created
May 10, 2025 13:55
-
-
Save sunmeat/5cbbf0d68d2cf925d3985af34b191994 to your computer and use it in GitHub Desktop.
state simple example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState} from 'react' | |
import './App.css' | |
const getRandomColor = () => { | |
const letters = '0123456789ABCDEF'; | |
let color = '#'; | |
for (let i = 0; i < 6; i++) { | |
color += letters[Math.floor(Math.random() * 16)]; | |
} | |
return color; | |
}; | |
function MyButton() { | |
const [color, setColor] = useState('blue'); // color - состояние, setColor - функция для его изменения | |
// деструктурирующее присваивание, useState возвращает массив с двумя элементами | |
return ( | |
<button style={{ backgroundColor: color }} onClick={() => setColor(getRandomColor())}> | |
Нажми меня | |
</button> | |
); | |
} | |
function BorderedButton() { | |
return ( | |
<div className="bordered"> | |
<MyButton /> | |
</div> | |
); | |
} | |
export class MyHeader extends React.Component { | |
render() { | |
return <h1>Hello</h1> | |
} | |
} | |
function App() { | |
return ( | |
<> | |
<MyButton/> | |
<MyHeader/> | |
<BorderedButton /> | |
</> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment