▶ DOM 요소의 id
<div id="my-element"></div>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.success {
background-color: green;
}
.failure {
background-color: red;
}
</style>
<script>
function validate() {
var input = document.getElementById('password');
input.className = '';
if(input.value === '0000') {
input.className = 'success';
} else {
input.className = 'failure';
}
}
</script>
</head>
<body>
<input type="password" id="password"/>
<button onclick="validate()">Validate</button>
</body>
</html>
▶ ValidationSample.css
.success {
background-color: lightgreen;
}
.failure {
background-color: lightcoral;
}
▶ ValidationSample.js
import {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 { Component } from 'react';
import ValidationSample from './ValidationSample';
class App extends Component{
render() {
return (
<ValidationSample/>
)
}
}
export default App;
▶ 콜백함수 사용 예시
<input ref={(ref) => {this.input=ref}} />
▶ createRef 사용 예시
import {Component} from 'react';
class RefSample extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
}
render() {
return (
<div>
<input ref={this.input} />
</div>
);
}
}
export default RefSample;
▶ ValidationSample.js의 input요소
(...)
<input
ref={(ref) => this.input=ref}
(...)
/>
handleButtonClick = () => {
this.setState({
clicked: true,
validated: this.state.password === '0000'
});
this.input.focus();
}
<MyComponenet
ref={(ref) => {this.myComponent=ref}}
/>
import { Component } from 'react';
class ScrollBox extends Component {
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 { Component } from 'react';
import ScrollBox from './ScrollBox';
class App extends Component{
render() {
return (
<ScrollBox/>
)
}
}
export default App;