Reactでドロップダウン選択を実装しています。
console.log(formData)でオブジェクトの中身を出力すると、
selectionの値が数値になっています。
画像は、'お問い合わせ内容3'を選択したパターンです。
こちらをlabelプロパティの'お問い合わせ内容1'のように出力させるようにしたいです。
そもそもなぜ数値が出力されるのかが不明でして、ご教示いただければと思います。
TypeScript
1// Settings > ContactSelect.tsx 2const SelectList = { 3 list: [ 4 { value: 'inquiry1', label: 'お問い合わせ内容1' }, 5 { value: 'inquiry2', label: 'お問い合わせ内容2' }, 6 { value: 'inquiry3', label: 'お問い合わせ内容3' }, 7 ] 8} 9 10export default SelectList;
TypeScript
1// Components > Form.tsx 2export function FormSelect(props: any) { 3 let classNames = 'form-control '; 4 if (props.className !== undefined){ 5 classNames += props.className; 6 } 7 8 return ( 9 <select {...props} className={classNames}> 10 <option hidden>{props.hiddenlabel}</option> 11 {props.options?.map((option: string, index: number) => { 12 return <option value={index+1} key={index}>{option}</option> 13 })} 14 </select> 15 ) 16} 17 18export default {};
TypeScript
1import React, { useState } from 'react'; 2import { Link } from 'react-router-dom'; 3import { FormSelect } from '../Components'; 4 5function ContactNew(props: any) { 6 function handleContactNew() { 7 console.log(formData) 8 } 9 10 type FormData = { 11 nickname :string, 12 email: string, 13 content: string, 14 selection: string, 15 } 16 17 const [ formData, setFormData ] = useState<FormData>({ 18 nickname: '', 19 email: '', 20 content: '', 21 selection: '', 22 }) 23 24 const onChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => { 25 e.persist(); 26 const { name, value } = e.target 27 setFormData({ ...formData, [name]: value }) 28 } 29 30 31 return ( 32 <> 33 // 略 nickname, email, content入力欄は省略 34 <FormSelect className='select' style={{ marginBottom: "20px"}} id="selection" name="selection" type='selectbox' 35 hiddenlabel='選択してください' 36 options={SelectList.list.map((option, key) => ( 37 <> 38 <option value={option.value} key={key}>{option.label}</option> 39 </> 40 ))} 41 onChange={onChangeHandler} value={formData.selection} 42 /> 43 <FormSubmit onClick={handleContactNew} /> 44 </> 45 ) 46} 47 48export default ContactNew;
回答1件
あなたの回答
tips
プレビュー