react(counter)
버튼을 누르면 숫자가 1씩 커지거나 작아지는 코드
<!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>Document</title>
<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/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class CounterFn extends React.Component{
constructor(props){
super(props)
this.state = {
number:0
}
console.log('생성자')
}
onUp = (e) => {
this.setState({number:this.state.number+1})
}
onDown = (e) => {
this.setState({number:this.state.number-1})
}
render(){
return(
<div>
{console.log('render')}
<h1>{this.state.number}</h1>
<button onClick={this.onUp}>+1</button>
<button onClick={this.onDown}>-1</button>
</div>
)
}
}
const Counter = () => {
console.log('function')
const [number,setNumber] = React.useState(0)
const onUp = () => {
setNumber ((s)=>s+1)
}
const onDown = () => {
setNumber((s)=>s-1)
}
return (
<div>
{console.log('render')}
<h1>{number}</h1>
<button onClick={onUp}>+1</button>
<button onClick={onDown}>-1</button>
</div>
)
}
ReactDOM.render(
<Counter/>,
document.querySelector('#root')
)
</script>
</body>
</html>
====================================================
<!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>Document</title>
<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/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props)
this.state = {
counter:0
}
}
onChange = (e) => {
this.setState({counter:e.target.value})
}
upBtn = (e) => {
this.setState({counter:this.state.counter+1})
}
downBtn = (e) => {
this.setState({counter:this.state.counter-1})
}
render(){
return(
<>
<input type="number" name="counter" value={this.state.counter}/>
<button onClick={this.upBtn}>+</button>
<button onClick={this.downBtn}>-</button>
</>
)
}
}
ReactDOM.render(
<App/>,
document.querySelector('#root')
)
</script>
</body>
</html>
Author And Source
이 문제에 관하여(react(counter)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@algml/reactcounter-b8l7jd0b저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)