코드 수정 전
import React from 'react'
export default function InputAndWarn({
type,
placeHolder,
pattern,
label,
required,
minlength,
maxlength,
onBlur
}) {
if (required) {
return (
<label>
<span>{label}</span>
{/* onFocus의 경우 어떤 곳에서든 기본적으로 작동하는 것일 때 */}
<input
type={type}
placeholder={placeHolder}
pattern={pattern}
minLength={minlength}
maxLength={maxlength}
onBlur={onBlur}
onFocus={(e) => {e.target.style.backgroundColor="red"}}
required
/>
</label>
)
} else {
return (
<label>
<span>{label}</span>
{/* onFocus의 경우 어떤 곳에서든 기본적으로 작동하는 것일 때 */}
<input
type={type}
placeholder={placeHolder}
pattern={pattern}
minLength={minlength}
maxLength={maxlength}
onBlur={onBlur}
onFocus={(e) => {e.target.style.backgroundColor="red"}}
/>
</label>
)
}
}
JavaScript
복사
if else로 조건에 따라 다른 return을 하도록 처리했는데, 코드가 좀 길어보여서 더 나은 방법은 없을지 고민됩니다.
코드 수정 후
import React from "react";
export default function InputAndWarn({
type,
placeHolder,
pattern,
label,
required,
minlength,
maxlength,
onBlur,
}) {
let inpEl = (
<input
type={type}
placeholder={placeHolder}
pattern={pattern}
minLength={minlength}
maxLength={maxlength}
onBlur={onBlur}
onFocus={(e) => {
e.target.style.backgroundColor = "red";
}}
/>
);
if (required) {
inpEl = (
<input
type={type}
placeholder={placeHolder}
pattern={pattern}
minLength={minlength}
maxLength={maxlength}
onBlur={onBlur}
onFocus={(e) => {
e.target.style.backgroundColor = "red";
}}
required
/>
);
}
return (
<label>
<span>{label}</span>
{inpEl}
</label>
);
}
JavaScript
복사