-
Notifications
You must be signed in to change notification settings - Fork 0
React Overview
Yongku cho edited this page Feb 9, 2021
·
10 revisions
JavaScript 함수이기 때문에 말 그래도 "함수 컴포넌트"라고 명명한다.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
<Welcome name="Sara" />
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
<Welcome name="Sara" />
- 상태 변경은
setState()
를 사용한다. -
this.state
은constructor
에서만 지정해야 한다.
import React from 'react';
import ReactDOM from 'react-dom';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}
}
componentDidMount() {
this.timerId = setInterval(
() => this.tick(),
1000
)
}
componentWillUnmount() {
clearInterval(this.timerId)
}
tick() {
this.setState({
date: new Date()
})
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}</h2>
</div>
)
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
- event는 브라우저 고유 이벤트가 아닌 합성 이벤트다.
function onClickButton(event) {}
<button onClick={onClickButton}></button>
<button onClick={(e) => this.deleteRow(id, e)}></button>
function UserGreeting (props) {
return <h1>Welcome back!</h1>
}
function GuestGreeting (props) {
return <h1>Please sign up.</h1>
}
function Greeting (props) {
return props.isLoggedIn ? <UserGreeting /> : <GuestGreeting />
}
컴포넌트를 변수에 담을 수 있다!
function Greeting (props) {
let button;
if (props.isLoggedIn) {
button = <UserGreeting />
} else {
button = <GuestGreeting />
}
return button
}
function Counter (props) {
return (
<div> { props.count && <h1>Message: {props.count}</h1>} </div>
)
}
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => (
<li key={number.toString()}>{number}</li>
))
- React state로 폼과 결합할 수 있다.
- 꼭 onChange 이벤트로 변경된 상태를 받아 state를 변경해줘야 한다.
class NameForm extends React.Component {
constructor(props) {
super(props)
this.state = {value: ''}
this.handleBlur = this.handleBlur.bind(this)
this.handleChange = this.handleChange.bind(this)
}
handleBlur () {
console.log(this.state.value)
}
handleChange(event) {
this.setState({value: event.target.value})
}
render() {
return (<input
type="text"
value={this.state.value}
onBlur={this.handleBlur}
onChange={this.handleChange}
/>)
}
}
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (<h1>Hello, {this.props.name}</h1>)
}
}
Greeting.propTypes = {
name: PropTypes.string
}
import PropTypes from 'prop-types';
function Greeting (props) {
return (<h1>Hello, {props.name}</h1>)
}
Greeting.propTypes = {
name: PropTypes.string
}