首页 > 解决方案 > 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)
};

标签: javascripthtmlreactjsformsecmascript-6

解决方案


首先,我建议您像这样为您的元素分配一个名称属性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);

推荐阅读