import React, { useState } from 'react';
const App = () => {
const [artistName, setArtistName] = useState("");
const [artistCompany, setArtistCompany] = useState("");
const [artistGenre, setArtistGenre] = useState("");
const [imageUri, setImageUri] = useState("");
const [description, setDescription] = useState("");
const [realName, setRealName] = useState("");
const [account, setAccount] = useState("");
const [bank, setBank] = useState("");
const onChangeArtistName = e => setArtistName(e.target.value);
const onChangeArtistCompany = e => setArtistCompany(e.target.value);
const onChangeArtistGenre = e => setArtistGenre(e.target.value);
const onChangeImageUri = e => setImageUri(e.target.value);
const onChangeDescription = e => setDescription(e.target.value);
const onChangeRealName = e => setRealName(e.target.value)
const onChangeAccount = e => setAccount(e.target.value);
const onChangeBank = e => setBank(e.target.value);
return (
<div>
<input name="artistName" value={artistName} onChange={onChangeArtistName} /><br/>
<input name="artistCompany" value={artistCompany} onChange={onChangeArtistCompany} /><br/>
<input name="artistGenre" value={artistGenre} onChange={onChangeArtistGenre} /><br/>
<input name="imageUri" value={imageUri} onChange={onChangeImageUri} /><br/>
<input name="description" style={{width: "550px", height: "300px"}}
value={description} onChange={onChangeDescription} /><br/>
<input name="realName" value={realName} onChange={onChangeRealName} /><br/>
<input name="account" value={account} onChange={onChangeAccount} /><br/>
<input name="bank" value={bank} onChange={onChangeBank} /><br/>
</div>
);
한 두개면 모를까 예시처럼 좀 많다 싶은 경우에는 onChange를 각각 만들어줘야 한다.
이는 매우 귀찮다.
그래서 해결책을 찾아봤는데, ES6 의 Spread syntax 를 활용하면 간편하게 선언할 수 있다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
import React, { useState } from 'react';
const App = () => {
const [inputs, setInputs] = useState({
artistName: "",
artistCompany: "",
artistGenre: "",
imageUri: "",
description: "",
realName: "",
account: "",
bank: ""
})
const {
artistName, artistCompany, artistGenre, imageUri,
description, realName, account, bank
} = inputs;
const onChange = e => {
setInputs({
...inputs,
[e.target.name]: e.target.value
});
};
return (
<div>
<input name="artistName" value={artistName} onChange={onChange} /><br/>
<input name="artistCompany" value={artistCompany} onChange={onChange} /><br/>
<input name="artistGenre" value={artistGenre} onChange={onChange} /><br/>
<input name="imageUri" value={imageUri} onChange={onChange} /><br/>
<input name="description" style={{width: "550px", height: "300px"}}
value={description} onChange={onChange} /><br/>
<input name="realName" value={realName} onChange={onChange} /><br/>
<input name="account" value={account} onChange={onChange} /><br/>
<input name="bank" value={bank} onChange={onChange} /><br/>
</div>
);
}
export default App;
useReducer로 해결하는 방법도 존재합니다