<input type="number" maxLength={4}>
<input type="text" maxLength={4}>
또는
<input type="number" max={9999}>
input의 type="number"
이면 입력되는 값이 숫자이므로 maxLength는 올바른 property가 아니다. type="number"
이면 max={9999}
를 주어 자리수를 4자리까지 제한할 수 있다.
하지만 나는 애초에 길이가 4자리를 초과해 작성되게 하지 않기 위함이었음으로 type="text"
로 변경해 입력되는 값이 문자열이 되게했다. 그래서 maxLength={4}
("4"로 해도 된다) 그대로 하고, onSubmitForm 함수 내부에서 parseInt(value) 했을때 NaN
이 반환된다면 오류로 처리하도록 했다.
setState()는 값의 변경에 상관없이 render() 함수를 실행시킨다.
state의 값이 변경되지 않음에도 렌더가 되는 문제가 발생할 수 있는데, 다음 방법들을 사용해 방지할 수 있다. (props의 비의도적인 렌더 오류도 방지 가능)
import React, { Component } from 'react';
export default class Tries extends Component {
shouldComponentUpdate(nextProps, nextState, nextContext) {
if (this.props.tryInfo.try !== nextProps.tryInfo.try) {
return true;
}
return false;
}
render() {
console.log('Try 컴포넌트가 렌더링 되었습니다.');
return (
<li>
<div>시도: {tryInfo.try}</div>
<div>결과: {tryInfo.result}</div>
</li>
);
};
};
참고 : shouldComponentUpdate() | React API
import React, { PureComponent } from 'react';
export default class Tries extends PureComponent {
render() {
console.log('Try 컴포넌트가 렌더링 되었습니다.');
return (
<li>
<div>시도: {tryInfo.try}</div>
<div>결과: {tryInfo.result}</div>
</li>
);
};
};
import React from 'react';
export const Tries = ({tryInfo}) => {
console.log('Try 컴포넌트가 렌더링되었습니다.');
return (
<li>
<div>시도: {tryInfo.try}</div>
<div>결과: {tryInfo.result}</div>
</li>
);
};
const MemorizedTries = React.memo(Tries);
export default MemorizedTries;
또는
import React from 'react';
const Tries = React.memo(({tryInfo}) => {
console.log('Try 컴포넌트가 렌더링되었습니다.');
return (
<li>
<div>시도: {tryInfo.try}</div>
<div>결과: {tryInfo.result}</div>
</li>
);
});
export default Tries;