리엑트에서 input 입력값 처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import './index.scss'

class Index extends Component {
constructor (props) {
super(props)

this.initialQ = this.props.q || ''
this.state = { q: this.initialQ }

}

handleInputChange = (e) => {
const target = e.target;
//const type = e.type;

const name = target.name;
const value = target.value.trim();
const modifiedValue = value.substring(0,10);

this.setState({
[name]: modifiedValue
});
}

handleInputPress = (e) => {
if (e.key === 'Enter') {
this.goSearch()
}
}

goSearch = (q = this.state.q) => {
if (q) {
this.props.history.push(`/search/${q}`)
}
}

render () {
return (
<React.Fragment>
<input type='text' name='q' className={`searchbox`}
value={this.state.q}
onChange={this.handleInputChange}
onKeyPress={this.handleInputPress}/>
</React.Fragment>
)
}
}

export default Index

Input 숫자 키패드

iOS 사파리에서는 maxLength가 먹지 않아 js로 막아야 합니다.

1
2
3
4
5
6
7
8
9
<input type='number'
pattern="[0-9]*"
placeholder='코드입력'
maxLength="6"
className={this.state.errorMsg && 'error'}
name= "inputCode"
value={this.state.inputCode}
onChange={this.handleInputChange}
onKeyPress={this.handleInputPress}/>