如何从下拉列表(REACT)中选择的API获取布尔数据?

时间:2019-09-12 12:56:55

标签: reactjs formik

我使用“ true”和“ false”选项创建了一个下拉列表。我从我的API中获得了表中的所有数据。

在更新时,我有一个获取行数据的表格。使用布尔值时,即使我将html类型设为“文本”,它也会变为true / false。

我想使用下拉菜单,但目前它是静态的,因此始终处于“ true”。

如何选择正确的值并更新更改?

toSelectOption.js

export const trueFalse = [
    { label: "true", value: "Y" },
    { label: "false", value: "F" }
];

Update.jsx

renderTrueFalse() {
    return trueFalse.map((item) => {
        if (this.state.showKey === true) {
            return (
                <option value={item.value}>{item.label}</option>
            );
        }
    });
}

    //...
    <Formik
        initialValues={{
            //...
            showKey,
            //...

        }}
        onSubmit={this.onSubmit}
        //...
        {
            (props) => (
                <Form>
                    //...

                        <Col md="3">
                            <FormGroup>
                                <label>Show Key</label>
                                <Field className="form-control" component="select"
                                       name="showKey">
                                    {this.renderTrueFalse()}
                                </Field>
                            </FormGroup>
                        </Col>

                    //...
                    <div className="d-flex justify-content-center">
                        <MDBBtn type="submit"
                                className="btn btn-outline-success waves-effect">Salva</MDBBtn>
                    </div>

                </Form>
            )
        }
    </Formik>
    //...     

1 个答案:

答案 0 :(得分:0)

我认为您在onChange组件上缺少<Field>事件处理程序。 尝试添加此内容:

Update.jsx

<Field className="form-control"
       component="select"
       name="showKey"
       onChange={e => this.handleOnChange(e)}
>

,然后在函数renderTrueFalse()下,添加以下内容:

handleOnChange = e => {
  console.log('value->', e.target.value) // e.target.value is your output (Y or F) from the select option
  // do whatever you wanna do here with the value from the option in this case ('Y' OR 'F')
}

打开develop Tools(F12),选择正确的选项后,您确实会收到updated value

在仅使用React here

的示例上进行检查

enter image description here