【问题标题】:React: Perform different operation depending on select option dropdownReact:根据选择选项下拉菜单执行不同的操作
【发布时间】:2019-10-31 07:23:46
【问题描述】:

我在 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)
};

【问题讨论】:

  • React 表单是有状态的。这意味着您需要将值存储在控制器组件中。完成后,您可以检查 this.state 中的值。阅读此页面了解如何在 React 中使用表单。 reactjs.org/docs/forms.html
  • @Kyle 你是说我需要在提交时为我的组件保存状态中的选项值,然后使用 this.state.optionValue,例如?
  • 这是推荐的方式,是的。
  • @Kyle 好的,只是出于好奇,我如何从选项中获取价值?我知道我可以这样做:this.setState({optionValue: event.data.option.value}),但我不确定在提交表单后如何获取选项值。非常感谢您的帮助。

标签: javascript html reactjs forms ecmascript-6


【解决方案1】:

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

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

那么您的条件检查将类似于:

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

【讨论】:

  • 对不起 event.target.value.option 不是一个东西。这只是我写的一些伪代码。
【解决方案2】:

首先,我建议您像这样为 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多