함수형
import React from 'react';
const App = () => {
const name = 'react';
return <div>{name}</div>
}
export default App;
클래스형
import React, {Component} from 'react';
class App extends Component {
render(){
const name = 'react';
return <div>{name}</div>
}
}
export default App;
함수형
import React, {useState} from 'react';
const MyComp = ({name, children}) => {
const [count, setCount] = useState(0);
return (
<div>
제 이름은 {name}입니다. <br />
children 값은 {children}입니다.<br />
count 는 {count}입니다.<br />
</div>
)
}
클래스형
import React, {Component} from 'react';
class MyComp extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
render() {
const { name, children } = this.props;
const { count } = this.state;
return (
<div>
제 이름은 {name}입니다. <br />
children 값은 {children}입니다.<br />
count 는 {count}입니다.<br />
</div>
)
}
}
클래스형
import React, { Component } from 'react';
class EventPractice extends Component {
state = {
username: '',
message: ''
}
handleChange = (e) => {
this.setState({
[e.target.name] : e.target.value
});
}
handleClick = () => {
alert(this.state.username + ': ' + this.state.message);
this.setState({
username: '',
message: ''
});
}
handleKeyPress = (e) => {
if(e.key === 'Enter') {
this.handleClick();
}
}
render() {
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="사용자명"
value={this.state.username}
onChange={this.handleChange}
/>
<input
type = "text"
name="message"
placeholder="아무거나 입력해 보세요"
value={this.state.message}
onChange={this.handleChange}
onKeyPress={this.handleKeyPress}
/>
<button onClick={this.handleClick}>확인</button>
</div>
);
}
}
export default EventPractice;
함수형
import React, { useState } from 'react';
const EventPractice = () => {
const [form, setForm] = useState({
username: '',
message: ''
});
const { username, message } = form;
const onChange = e => {
const nextForm = {
...form,
[e.target.name]: e.target.value
};
setForm(nextForm);
};
const onClick = () => {
alert(username + ': ' + message);
setForm({
username: '',
message: ''
});
};
const onKeyPress = e => {
if (e.key === 'Enter') {
onClick();
}
};
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="사용자명"
value={username}
onChange={onChange}
/>
<input
type = "text"
name="message"
placeholder="아무거나 입력해 보세요"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
/>
<button onClick={onClick}>확인</button>
</div>
);
};
export default EventPractice;