개발자
input을 여러 개 관리해야 하는데 이름, 나이 이런 input 관리가 아닌 항목 추가(카카오톡 투표하기)처럼 name으로 구별하기 어려운 inputs를 구현하고 있는데(단순한content로 되어있습니다.) onChange를 어떻게 처리를 해야 줘하는지 감이 안 잡히는데 구현해 보신 분 있으실까요? 이 input들은 최대 30개까지 추가가 됩니다. +) 추가되는 인풋을 component로 따로 빼서 구현했습니다. const [contents, setContents] = useState([ { id: 1, content: '' }, { id: 2, content: '' } ]) {contents.map(() => ( <Input/> 이런식으로 되어있습니다!!!
답변 2
정답이라고 할 순 없지만 저라면 useReducer를 사용할것 같습니다. 도움이 되셨음 좋겠네요
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 27const reducer = (state, action) => { switch(action.type) { case 'UPDATE': case 'ADD': return { ...state, [action.key]: action.value }; case 'REMOVE': const {[action.key]: deleted, ...others} = state return others; } } const [status, dispatch] = useReducer(reducer , {}) //input 추가 const addInput = () => { dispatch({type: 'ADD', key: (UUID, hash 같은 임의의 key값), value: null}) } //input 삭제 const addInput = () => { dispatch({type: 'REMOVE', key: (삭제하려는 input의 key값)}) } {Object.keys(status).map((item) => ( <Input onChange={e => dispatch({type: 'UPDATE', key: item, value: e.target.value})}/> }
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
지금 가입하면 모든 질문의 답변을 볼 수 있어요!