反应:根据选择选项下拉菜单执行不同的操作

时间:2019-06-17 16:53:11

标签: javascript html reactjs forms ecmascript-6

我在React中有以下形式。我想做的是,如果select标记中的选项为“参与”,则发送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)
};

2 个答案:

答案 0 :(得分:1)

要以“反应”方式进行操作,您需要捕获选择框onChange事件:

<select onChange={e=>this.setState({selectedOption:e.target.value})} className="ui compact selection dropdown">

然后,您的状况检查将类似于:

if (this.state.selectedOption === 'participate') {...

答案 1 :(得分:1)

首先,我建议您为这样的select元素分配 name 属性

<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);