[스터디]리액트를 다루는 기술-ref:DOM에 이름달기

예제 컴포넌트 생성

// ValidationSample.css
.success {
    background-color: lightgreen;
}

.failure {
    background-color: lightcoral;
}

// ValidationSample.js
import React, { Component } from 'react';
import './ValidationSample.css';

class ValidationSample extends Component {
    state = {
        password: '',
        clicked: false,
        validated: false
    };

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

    handleButtonClick = () => {
        this.setState({
            clicked: true,
            validated: this.state.password === '0000'
        });
    };

    render() {
        return (
            <div>
                <input
                    type="password"
                    value={this.state.password}
                    onChange={this.handleChange}
                    className={
                        this.state.clicked
                            ? this.state.validated
                                ? 'success'
                                : 'failure'
                            : ''
                    }
                />
                <button onClick={this.handleButtonClick}>검증하기</button>
            </div>
        );
    }
}

export default ValidationSample;

// App.js
import React, { Component } from 'react';
import ValidationSample from './ValidationSample';

class App extends Component {
    render() {
        return <ValidationSample />;
    }
}
export default App;

input에 ref 달기

// ValidationSample.js
import React, { Component } from 'react';
import './ValidationSample.css';

class ValidationSample extends Component {
    state = {
        password: '',
        clicked: false,
        validated: false
    };

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

    handleButtonClick = () => {
        this.setState({
            clicked: true,
            validated: this.state.password === '0000'
        });
        this.myInput.focus();
    };

    render() {
        return (
            <div>
                <input
                    ref={ref => (this.myInput = ref)} // 콜백함수를 전달하여 myInput에 자기자신을 할당한다.
                    type="password"
                    value={this.state.password}
                    onChange={this.handleChange}
                    className={
                        this.state.clicked
                            ? this.state.validated
                                ? 'success'
                                : 'failure'
                            : ''
                    }
                />
                <button onClick={this.handleButtonClick}>검증하기</button>
            </div>
        );
    }
}

export default ValidationSample;

컴포넌트에 ref달기

// ScrollBox.js
import React, { Component } from 'react';

class ScrollBox extends Component {
    scrollToBottom = () => {
        const { scrollHeight, clientHeight } = this.box;
        this.box.scrollTop = scrollHeight - clientHeight;// 스크롤을 내리기 위해 스크롤바 위치를 계산한다.
  };

    render() {
        const style = {
            border: '1px solid black',
            height: '300px',
            width: '300px',
            overflow: 'auto',
            position: 'relative'
        };

        const innerStyle = {
            width: '100%',
            height: '650px',
            background: 'linear-gradient(white, black)'
        };

        return (
            <div style={style} ref={ref => (this.box = ref)}>
                <div style={innerStyle}/>
            </div>
        );
    }
}

export default ScrollBox;



// App.js
import React, { Component } from 'react';
import ScrollBox from './ScrollBox';

class App extends Component {
    render() {
        return (
            <div>
                <ScrollBox ref={ref => (this.scrollBox = ref)} />
                <button
                    onClick={() => {
                        this.scrollBox.scrollToBottom();//스크롤을 맨 밑으로 옮긴다.
                   }}
                >
                    맨 밑으로
                </button>
            </div>
        );
    }
}

export default App;

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다