React Overview - ChoDragon9/posts GitHub Wiki
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
}