如何在React中绑定下拉列表中的值?

时间:2019-05-13 15:35:30

标签: reactjs drop-down-menu

我正在尝试从下拉列表中获取ID的值以发布到API,但我不确定如何做到这一点。我会提供任何帮助

我尝试将onchange与handleChange函数一起使用,但是它什么也没做。下面是该表单和表单发布的react文件

import React from "react";
import { updateUsers, fetchUsers } from "./actions/appactions";
import FormChange from "./formchange";
var createReactClass = require("create-react-class");
const Update = createReactClass({
  getIntitialState() {
    return {
      users: []
    };
  },
  componentWillReceiveProps(props) {
    this.setState(props);
  },
  componentDidMount() {
    fetchUsers(this.props.match.params.usersId)
      .then(resp => resp.json())
      .then(data => {
        // this.setState({
        //   users: data
        // });
        this.setState(state => {
          state.users = data;
          return state;
        });
      })
      .catch(err => {
        console.error("error", err);
      });
  },
  handleSubmit(data) {
    updateUsers(this.state.users.id, data);
  },
  render() {
    return (
      <div>
        <FormChange
          onSubmit={this.handleSubmit}
          password={this.state.users.password}
        />
      </div>
    );
  }
});
export default Update;

import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
const Form2 = createReactClass({
  //setting initial state
  getInitialState() {
    return {
      customerName: this.props.customerName,
      email: this.props.email,
      businessName: this.props.businessName,
      address: this.props.address,
      city: this.props.city,
      lga: this.props.lga,
      url: this.props.url,
      description: this.props.description,
      obj: []
    };
  },
  componentDidMount() {
    this.fetchOptions();
  },
  fetchOptions() {
    fetch("https://localhost:44341/api/categories")
      .then(res => res.json())
      .then(json => {
        this.setState({
          obj: json
        });
      });
  },
  handleCustomerChange(e) {
    this.setState({
      customerName: e.target.value
    });
  },
  handleEmailChange(e) {
    this.setState({
      email: e.target.value
    });
  },
  handleBusinessChange(e) {
    this.setState({
      businessName: e.target.value
    });
  },
  handleAddressChange(e) {
    this.setState({
      address: e.target.value
    });
  },
  handleCityChange(e) {
    this.setState({
      city: e.target.value
    });
  },
  handleLgaChange(e) {
    this.setState({
      lga: e.target.value
    });
  },
  handleUrlChange(e) {
    this.setState({
      url: e.target.value
    });
  },
  handleDescriptionChange(e) {
    this.setState({
      description: e.target.value
    });
  },
  handleCatChange(e) {
    this.setState({
      obj: e.target.value
    });
  },
  handleSubmit(e) {
    e.preventDefault();
    this.props.onSubmit(this.state);
  },
  render() {
    return (
      <form
        name="categories_post"
        className="form-horizontal"
        onSubmit={this.handleSubmit}
      >
        <div id="business_post">
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="customerName"
            >
              Customer Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.customerName}
                onChange={this.handleCustomerChange}
                id="customerName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="email">
              Email
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.email}
                onChange={this.handleEmailChange}
                id="email"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="businessName"
            >
              Business Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.businessName}
                onChange={this.handleBusinessChange}
                id="businessName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="address"
            >
              Address
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.address}
                onChange={this.handleAddressChange}
                id="address"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="city">
              City
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.city}
                onChange={this.handleCityChange}
                id="city"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="lga">
              LGA
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.lga}
                onChange={this.handleLgaChange}
                id="lga"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="url">
              URL
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.url}
                onChange={this.handleUrlChange}
                id="url"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="description"
            >
              Description
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.description}
                onChange={this.handleDescriptionChange}
                id="description"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="email">
              categories name
            </label>
            <div className="drop-down">
              <select>
                {this.state.obj.map(obj => {
                  return (
                    <option key={obj.id} value={obj.id}>
                      {obj.categoryName}
                    </option>
                  );
                })}
              </select>
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button
                type="submit"
                id="categoriesSubmit"
                className="btn btn-default"
              >
                submit
              </button>
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button className="btn btn-danger .mt-3">
                <Link to="/business">Home</Link>
              </button>
            </div>
          </div>
        </div>
      </form>
    );
  }
});

export default Form2;

2 个答案:

答案 0 :(得分:1)

更新

使用react-select,它能够优雅地处理id和值。 你可以试试看吗?

npm install react-select

import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
import Select from 'react-select';

const Form2 = createReactClass({
  //setting initial state
  getInitialState() {
    return {
      customerName: this.props.customerName,
      email: this.props.email,
      businessName: this.props.businessName,
      address: this.props.address,
      city: this.props.city,
      lga: this.props.lga,
      url: this.props.url,
      description: this.props.description,
      obj: []
    };
  },
  componentDidMount() {
    this.fetchOptions();
  },
  fetchOptions() {
    fetch("https://localhost:44341/api/categories")
      .then(res => res.json())
      .then(json => {
        this.setState({
          obj: json
        });
      });
  },
  handleCustomerChange(e) {
    this.setState({
      customerName: e.target.value
    });
  },
  handleEmailChange(e) {
    this.setState({
      email: e.target.value
    });
  },
  handleBusinessChange(e) {
    this.setState({
      businessName: e.target.value
    });
  },
  handleAddressChange(e) {
    this.setState({
      address: e.target.value
    });
  },
  handleCityChange(e) {
    this.setState({
      city: e.target.value
    });
  },
  handleLgaChange(e) {
    this.setState({
      lga: e.target.value
    });
  },
  handleUrlChange(e) {
    this.setState({
      url: e.target.value
    });
  },
  handleDescriptionChange(e) {
    this.setState({
      description: e.target.value
    });
  },
  handleCatChange(e) {
    this.setState({
      obj: e.target.value
    });
  },
  handleSubmit(e) {
    e.preventDefault();
    this.props.onSubmit(this.state);
  },

handleChange = (selectedOption) => {
   // this.setState({ selectedOption }); add it to state
    console.log(`Option selected:`, selectedOption);
  },

  render() {
    return (
      <form
        name="categories_post"
        className="form-horizontal"
        onSubmit={this.handleSubmit}
      >
        <div id="business_post">
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="customerName"
            >
              Customer Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.customerName}
                onChange={this.handleCustomerChange}
                id="customerName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="email">
              Email
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.email}
                onChange={this.handleEmailChange}
                id="email"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="businessName"
            >
              Business Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.businessName}
                onChange={this.handleBusinessChange}
                id="businessName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="address"
            >
              Address
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.address}
                onChange={this.handleAddressChange}
                id="address"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="city">
              City
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.city}
                onChange={this.handleCityChange}
                id="city"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="lga">
              LGA
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.lga}
                onChange={this.handleLgaChange}
                id="lga"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="url">
              URL
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.url}
                onChange={this.handleUrlChange}
                id="url"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="description"
            >
              Description
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.description}
                onChange={this.handleDescriptionChange}
                id="description"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="email">
              categories name
            </label>
            <div className="drop-down">
                <Select
                value={selectedOption}
                onChange={this.handleChange}
                options={this.state.obj}
              />
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button
                type="submit"
                id="categoriesSubmit"
                className="btn btn-default"
              >
                submit
              </button>
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button className="btn btn-danger .mt-3">
                <Link to="/business">Home</Link>
              </button>
            </div>
          </div>
        </div>
      </form>
    );
  }
});

export default Form2;

react-select docs

答案 1 :(得分:0)

我已经解决了

//handlecatchange
  handleCatChange() {
    var value = ReactDOM.findDOMNode(this.refs.categoryId).value;
    this.setState({
      categoryId: parseInt(value)
    });
  },

下拉列表

<div className="drop-down">
              {/* <Select value={selectedOption} onChange={this.handleChange} options={this.state.obj}></Select> */}
              <select ref="categoryId" onChange={this.handleCatChange}>
                {this.state.obj.map(obj => {
                  return (
                    <option
                      key={obj.id}
                      value={obj.id}
                      onChange={this.handleCatChange}
                    >
                      {obj.categoryName}
                    </option>
                  );
                })}
              </select>
</div>