javascript - React:根据选择选项下拉菜单执行不同的操作
问题描述
我在 React 中有以下表格。如果选择标签中的选项是参与,我想要做的是发送一个 POST 请求。
<form action={this.props.action} method="POST" onSubmit={this.handleSubmit}>
<div className="ui action input">
<input type="text" placeholder="Enter code" name="code"/>
<select className="ui compact selection dropdown">
<option value="participate">Participate!</option>
<option value="check_status">Check status</option>
</select>
<button>
Submit
</button>
</div>
</form>
这是我的 handleSubmit 函数:
handleSubmit = (event) => {
event.preventDefault();
// HERE I want to check if the option as Participate, and then to the following code:
// Sudo code here
// IF STATEMENT event.target.value.option === 'participate'
const data = {id: this.state.code, is_winner: true};
fetch('/api/add_user', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(data),
})
.then(res => res.json());
// ElSE
// DO NOT SOMETHING ELSE (NOT POST)
};
解决方案
首先,我建议您像这样为您的元素分配一个名称属性select
<select name="my-dropdown" className="ui compact selection dropdown">
然后在您的handleEvent方法中,您可以访问表单中的值
const elementRef = Array.from(event.target.elements).find(
e => e.name === "my-dropdown"
);
// Here is the value from your dropdown selection
// that you can use to perform requests
console.log("Selection Value", elementRef.value);
推荐阅读
- spring - jhispter 自定义 webflux 安全异常
- php - 带有来自 dbase 的 if 和 else 条件值的滑动条 php
- javascript - 无法让 Mapbox SDK 识别 geocodeForward 请求中的模糊匹配属性
- javascript - 使用 JavaScript 将任何日期格式转换为 en-US(mm/dd/yyyy hh:mm:ss)
- javascript - 如何解决 window.open() 的选项在 Edge 上不起作用
- javascript - 根据百分比拒绝输入
- php - 定义与同一模型的关系(自连接)Laravel - 找不到类'App\Models\App\Models\Contact_cats' laravel 8
- python - 我的最后一个函数出现了 TypeError。我怎么称呼他们?另外,我如何找到所有内容的总数和平均值?我迷路了
- postgresql - AWS API Gateway Error: Proxy integrations cannot be configured to transform responses
- huggingface-transformers - 如何在transformer huggingface上加入命名实体识别任务产生的子词?