首页 > 解决方案 > 在表单中设置值在反应中选择

问题描述

当我单击按钮时,我希望该按钮在反应中设置选择的值。假设我的列表有 = 10,15,20,25,30 根据代码,该值设置为 10 默认值,因为它是数组中的第一个对象。

我想要的是,当我单击按钮时,我希望将值设置为 25 。

const [formData,setFormData] =useState({name:'',age:''})

//this is form submit
const handleSubmit = (event)=>{
setFormData({age:event.target.age.value})
}

//this will be my another button which will set my value to 25
//const randomButton = () => {}

<select
className='custom-select'
id='age'
name='age'
required
>
{ageOptions.map((row,index)=>{return <option value={row.value}>{row.label}</option>})}
</select>

标签: javascripthtmlreactjsformsselect

解决方案


Something like that ? :

    

import React, { useState } from "react";

const options = [
  { label: "rep 1", value: "first" },
  { label: "rep 2", value: "second" },
  { label: "rep 3", value: "third" },
];


    export default function App() {
      const [val, setVal] = React.useState("zero")
    
      const goTwo = () => setVal('second')
    
      const handleChange = (inp) => setVal(inp.target.value)
    
      return (
        <div >
            <button onClick={goTwo}>Go Two</button>
            <select
              onChange={handleChange} >{options.map(e=><option value={e.value} selected={e.value===val?'selected':''}>{e.label}</option>)}
            </select>
            --> {val}
        </div>
      )
    }

https://codesandbox.io/s/hopeful-margulis-h6dgi?file=/src/App.js


推荐阅读