반응형

Props

App.js

import React from 'react';
import Student from './Student';

export default class App extends React.Component {
    constructor() {
        super();
    }

    render() {
        const sayHi = () => {
            alert("Hi");
        };

        return (
            <div>
                <Student number={100} onClick={sayHi}>john</Student>
            </div>
        )
    }
};

Student.js

import React from 'react';
import PropTypes from 'prop-types';

export default class Student extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                {this.props.number}
                {this.props.major}
                {this.props.children}
                <button onClick={this.props.onClick}>Say Hi</button>
            </div>
        );
    }
};

Student.propTypes = {
    number: PropTypes.number.isRequired,
    major: PropTypes.string,
    onClick: PropTypes.func
};

Student.defaultProps = {
    major: 'computer'
};

State

App.js

import React from 'react';
import Student from './Student';

export default class App extends React.Component {
    render() {
        return (
            <div>
                <Student/>
            </div>
        )
    }
};

Student.js - 방식1

import React from 'react';

export default class Student extends React.Component {
    constructor() {
        super();

        this.state = {
            number: 100,
            name: 'john'
        };

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {
        this.setState({
            name: e.target.value
        });
    }

    /*
    // 위와 동일하지만 비권장
    handleChange(e) {
        this.state.name = e.target.value;
        this.forceUpdate();        
    }
    */

    render() {
        return (
            <div>
                <div>{this.state.number} {this.state.name}</div>
                <input value={this.state.name} onChange={this.handleChange}/>
            </div>
        );
    }
};

Student.js - 간단한 방법

import React from 'react';

export default class Student extends React.Component {
    state = {
        number: 100,
        name: 'john'
    };

    handleChange = (e) => {
        this.setState({
            name: e.target.value
        });
    };

    render() {
        return (
            <div>
                <div>{this.state.number} {this.state.name}</div>
                <input value={this.state.name} onChange={this.handleChange}/>
            </div>
        );
    }
};

for

App.js

import React from 'react';
import Student from './Student';

export default class App extends React.Component {
    constructor() {
        super();

        this.state = {
            studentList: [
                { number: 100, name: 'john-0' },
                { number: 101, name: 'john-1' },
                { number: 102, name: 'john-2' }
            ]
        }
    }

    render() {
        return (
            <div>
                {
                    this.state.studentList.map((student) => {
                        return (
                            <Student number={student.number}>{student.name}</Student>
                        );
                    })
                }
            </div>            
        )
    }
};

Student.js

import React from 'react';

export default class Student extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (
            <div>{this.props.number} {this.props.children}</div>
        );
    }
};

change list state

App.js

import React from 'react';
import Student from './Student';
import update from 'react-addons-update';

export default class App extends React.Component {
    constructor() {
        super();

        this.state = {
            lastNumber: 2,
            studentList: [
                { number: 0, name: 'john-0' },
                { number: 1, name: 'john-1' },
                { number: 2, name: 'john-2' }
            ]
        };

        this.add = this.add.bind(this);        
        this.remove = this.remove.bind(this);
        this.change = this.change.bind(this);
    }

    add() {
        let newNumber = this.state.lastNumber + 1;

        this.setState({
            studentList: update(
                this.state.studentList, 
                {
                    $push: [
                        { number: newNumber, name: 'john-' + newNumber }
                    ]
                }
            ),
            lastNumber: newNumber
        });
    }

    remove() {
        this.setState({
            studentList: update(
                this.state.studentList,
                {
                    $splice: [
                        [ this.state.lastNumber, 1 ]
                    ]
                }
            ),
            lastNumber: this.state.lastNumber - 1
        });
    }

    change() {
        let index = 0;

        this.setState({
            studentList: update(
                this.state.studentList,
                {
                    [ index ]: {
                        number: { $set: -100 },
                        name: { $set: 'john-???' }
                    }
                }
            )
        });
    }

    render() {
        return (
            <div>
                <button onClick={this.add}>add</button>
                <button onClick={this.remove}>remove</button>
                <button onClick={this.change}>change</button>
                {
                    this.state.studentList.map((student, i) => {
                        return (
                            <Student number={student.number} key={i}>{student.name}</Student>
                        );
                    })
                }              
            </div>            
        )
    }
};

Student.js

import React from 'react';

export default class Student extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (
            <div>{this.props.number} {this.props.children}</div>
        );
    }
};

ref

App.js

import React from 'react';

export default class App extends React.Component {
    constructor() {
        super();

        this.handleKeyPress = this.handleKeyPress.bind(this);
    }

    handleKeyPress(e) {
        if (e.charCode === 13) {
            this.nextInput.focus();
        }
    }

    render() {
        return (
            <div>
                <input onKeyPress={this.handleKeyPress} placeholder='엔터를 누르면 다음 input으로 포커싱'/>
                <br/>
                <input ref={(ref) => { this.nextInput = ref }}/>
            </div>
        )
    }
};

Life Cycle

App.js

import React from 'react';
import Child from './Child';

export default class App extends React.Component {
    constructor() {
        super();

        this.state = {
            number: 0
        };

        this.onClick = this.onClick.bind(this);
    }

    onClick() {
        this.setState({
            number: this.state.number + 1
        });
    }

    render() {
        return (
            <div>
                <button onClick={this.onClick}>increase</button>
                <Child number={this.state.number}/>
            </div>
        )
    }
};

Child.js

import React from 'react';

export default class App extends React.Component {
    constructor() {
        super();

        console.log("constructor()");
    }

    componentWillMount() {
        console.log("componentWillMount()", "렌더링이 되기 전 실행 (DOM 처리 불가)");
    }

    componentDidMount() {
        console.log("componentDidMount()", "렌더링이 된 후 실행 (DOM 처리 가능)");
    }

    componentWillReceiveProps(nextProps) {
        console.log("componentWillReceiveProps()", "새로운 props를 받았을 때 실행 (setState 사용 가능)", JSON.stringify(nextProps));
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log("shouldComponentUpdate()", "props/state가 변경되었을 때 리렌더링 할지말지 결정", JSON.stringify(nextProps), JSON.stringify(nextState));
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
        console.log("componentWillUpdate()", "컴포넌트가 Update 되기 전 실행 (setState 사용 불가 - 무한루프 발생)", JSON.stringify(nextProps), JSON.stringify(nextState));
    }

    componentDidUpdate(prevProps, prevState) {
        console.log("componentDidUpdate()", "컴포넌트가 Update 된 후 실행 (setState 사용 불가 - 무한루프 발생)", JSON.stringify(prevProps), JSON.stringify(prevState));
    }

    componentWillUnmount() {
        console.log("componentWillUnmount()", "컴포넌트가 제거될 때 실행");
    }

    render() {
        console.log("render()");

        return (
            <div>
                {this.props.number}
            </div>
        )
    }
};

Local Storage

App.js

import React from 'react';
import Student from './Student';
import update from 'react-addons-update';

export default class App extends React.Component {
    constructor() {
        super();

        this.state = {
            lastNumber: 2,
            studentList: [
                { number: 0, name: 'john-0' },
                { number: 1, name: 'john-1' },
                { number: 2, name: 'john-2' }
            ]
        };

        this.add = this.add.bind(this);
        this.clearLocalStorage = this.clearLocalStorage.bind(this);
    }

    componentWillMount() {
        const studentList = localStorage.studentList;

        if (studentList) {
            this.setState({
                studentList: JSON.parse(studentList)
            });
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (JSON.stringify(prevState.studentList) != JSON.stringify(this.state.studentList)) {
            localStorage.studentList = JSON.stringify(this.state.studentList);
        }
    }

    add() {
        let newNumber = this.state.lastNumber + 1;

        this.setState({
            studentList: update(
                this.state.studentList, 
                {
                    $push: [
                        { number: newNumber, name: 'john-' + newNumber }
                    ]
                }
            ),
            lastNumber: newNumber
        });
    }

    clearLocalStorage() {
        localStorage.clear();
    }

    render() {
        return (
            <div>
                <button onClick={this.add}>add</button>
                <button onClick={this.clearLocalStorage}>clear</button>
                {
                    this.state.studentList.map((student, i) => {
                        return (
                            <Student number={student.number} key={i}>{student.name}</Student>
                        );
                    })
                }              
            </div>            
        )
    }
};

Student.js

import React from 'react';

export default class Student extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (
            <div>{this.props.number} {this.props.children}</div>
        );
    }
};
반응형

'Development > React' 카테고리의 다른 글

[React] Hooks  (0) 2019.05.15
[React] MobX  (0) 2019.05.14
[React] Redux  (0) 2019.05.14
[React] Visual Studio Code 설정  (0) 2019.05.05
[React] 프로젝트 설정  (0) 2019.05.05

+ Recent posts