1. Sử dụng Hook
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ReactJS</title> </head> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script type="text/babel"> const { useState } = React; const App = (props) => { const [count, setCount] = useState(0) return ( <div> <h3>{ props.title }</h3> <p>Count: { count }</p> <button onClick={() => { setCount(count + 1) }}>Increase</button> <button onClick={() => { setCount(count - 1) }}>Decrease</button> </div> ); } ReactDOM.render( <App title="Hook - Demo state and prop" />, document.getElementById('root') ); </script> </body> </html> |
2. Sử dụng Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ReactJS</title> </head> <body> <div id="root"></div> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script type="text/babel"> class App extends React.Component { constructor(props) { super(props); this.state = { count: 1 } }; render() { return ( <div> <h3>{ this.props.title }</h3> <p>Count: { this.state.count }</p> <button onClick={() => { this.setState({ count: this.state.count + 1 }) }}>Decrease</button> <button onClick={() => { this.setState({ count: this.state.count - 1 }) }}>Decrease</button> </div> ); } } ReactDOM.render( <App title="Class Component - Demo state and props"/>, document.getElementById('root') ); </script> </body> </html> |