前提・実現したいこと
Reactでラジオボタンを持った複数のフォームをmapで表示しているのですが、二つ目以降のラジオボタンの値を変更しても、一つ目のラジオボタンの値が変更されます。
どのようにすれば対応できますでしょうか?
該当のソースコード
React.js
1[親コンポーネント] 2... 3 const renderTagContent = () => { 4 return video.map( 5 v => v.tags.map( t => 6 <TagContent 7 key={t.id} 8 {...t} /> 9 ) 10 ) 11 } 12 13 return( 14 { renderTagContent() } 15 ) 16...
React.js
1[子コンポーネント(Form)] 2... 3 const initialState = { 4 'action_type': props.action_type, 5 } 6 7 const [tag, setTag] = useState(initialState); 8 9 const handleChange = (e) => { 10 const value = e.target.value; 11 setTag({ 12 ...tag, 13 [e.target.name]: value 14 }); 15 } 16 17 return( 18 <div> 19 <label htmlFor="a">a</label> 20 <input id="a" type='radio' name='action_type' value='a' checked={ tag.action_type === 'a' } onChange={ (e) => handleChange(e) } /> 21 <label htmlFor="b">b</label> 22 <input id="b" type='radio' name='action_type' value='b' checked={ tag.action_type === 'b' } onChange={ (e) => handleChange(e) } /> 23 <label htmlFor="c">c</label> 24 <input id="c" type='radio' name='action_type' value='c' checked={ tag.action_type === 'c' } onChange={ (e) => handleChange(e) } /> 25 </div> 26 ) 27...
###追記
JSON
1videoの中身 2[ 3 { 4 id: 'id', 5 tags: [ 6 { 7 id: 'id', 8 action_type: '' //a or b or c 9 }, 10 { 11 id: 'id', 12 action_type: '' //a or b or c 13 } 14 ] 15 }, 16 { 17 id: 'id', 18 tags: [ 19 { 20 id: 'id', 21 action_type: '' //a or b or c 22 } 23 ] 24 }, 25]
タグコンテント内に親コンポーネントから引き継いだ情報をstateで管理し、それぞれのhandleChange関数でstateを変更しています。
確認してみると、handleChange関数がラジオボタンの時のみ一つ目の物しか動いていないようです。
回答1件
あなたの回答
tips
プレビュー