javascript - 在表单中设置值在反应中选择
问题描述
当我单击按钮时,我希望该按钮在反应中设置选择的值。假设我的列表有 = 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>
解决方案
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
推荐阅读
- mongodb - 这个关于在 MongoDB 中预填充数据的提示是否正确?
- java - 使用
在 MyBatis3 中,项目列表为 NULL - android - Flutter Switch 在 Android 上没有动画,但在 iOS 上
- sql-server - 从 BLOB 数据库备份中获取逻辑文件名
- ruby-on-rails - 通过免费服务向手机号码发送短信
- akka - 我们可以在终止消息中区分 Actor Termination 吗?
- c - 我需要实现 PI 控制器反馈来纠正失真的正弦波。将使用参考正弦波以产生错误
- c# - 如何使用 linq 更新数据库中的数据
- spring-boot - 如何在 Spring Boot 中实现高并发
- date - Interpret ISO week-of-year in gnu coreutils