尝试使用Form.Select和Semantic-UI-React从下拉列表选择中获取id值?

问题描述 投票:0回答:2

我在我的React / Rails项目中使用Semantic-UI-React并尝试在模式中使用更大形式的Form.Select下拉菜单。我需要从显示用户.name(animal.gnames)的选择中获取.id(animal.id)值 - gnmaes只是我为了自己的目的而使用的属性,以避免混淆。

我是Form.Select的options=道具,我映射了一个项目数组,然后将item.gname分配给title以获得一个很好的用户名下拉列表。然后我需要获取此大数组中的id并将其发送到获取请求。我已尝试过各种道具组合但无法从阵列中获取id并同时显示名称。

这是代码。我切断了后半部分,因为它与问题无关:


import React, { Component } from "react";
import { withRouter } from "react-router-dom"
import ActiveStorageProvider from 'react-activestorage-provider'
import { Menu, Button, Modal, Header, Icon, Image, Form, Input, Select, Label } from "semantic-ui-react"
import { Link } from "react-router-dom"
const value = null
const options = null

class Navigation extends Component {

  state = { modalOpen: false,
            title: "",
            body: "",
            animal: "",
            geotag: false,
            animals: []
          };

  componentDidMount() {
   fetch('http://localhost:9000/api/v1/animals')
   .then(r => r.json())
   .then(animals => {
     this.setState({ animals: animals })
   })
 };

  handlechange = (event) => {
    this.setState({ [event.target.name]: event.target.value })
  };

  submitForm = (event) => {
    this.props.postSighting(this.state.title, this.state.body) 
    // NEED TO GET ANIMAL.ID IN HERE!!!
  };

  // THIS METHOD IS READY TO GO FOR DOING THE ITERATION AND SET STATE BUT COULD NOT GET IT OT WORK. 
  // HAD ISSUE WITH A FETCH AND SET STATE LOOP CALLS

  selectAnimal = () => {
    const mappedAnimals = this.state.animals.map(animal => {
      this.setState({ animal: animal.gname })
    })
    return mappedAnimals
  };


  render () {
    return (

//.......SKIP TO THE CODE THAT MATTERS

          <Form.Select
               label="Animal"
               name="Animal"
               onChange={this.handlechange}
               selection= // WHAT GOES HERE?
               width={8}
               value= // WHAT GOES HERE?
               compact
               options={this.state.animals.map(animal => ({
                 return
                    name: animal.id,
                    key: animal.id,
                    value: animal.id,
                    text: animal.gname
               }))}
           /> // HOW DO I GET ANIMAL.ID TO MY SUBMIT FORM FUNCTION? 


reactjs forms modal-dialog semantic-ui-react
2个回答
0
投票

这里有很多内容,所以让我试着在代码注释中分解这一部分。如果有什么不清楚,请告诉我。

class Navigation extends Component {
  state = {
    modalOpen: false,
    title: "",
    body: "",
    animal: "",
    geotag: false,
    animals: []
  };

  componentDidMount() {
    fetch("http://localhost:9000/api/v1/animals")
      .then(r => r.json())
      .then(animals => {
        this.setState({ animals: animals });
      });
  }

  /**
   * When a user selects an option in the dropdown, the following will happen:
   *  1. this.handlechange gets called, where event.target.name === 'Animal'
   *     and event.target.value is the id of the animal selected
   *  2. Component's state gets updated to look like:
   *      {
   *        ...state,
   *        "Animal": <id of animal selected>
   *      }
   * Side note: you will have to access this "Animal" value through this.state.Animal
   * where the uppercase 'A' is very important. This is really prone to typos and not
   * recommended. To fix this I would change your <Form.Select> to have a lowercase
   * name attribute.
   */
  handlechange = (event, { name, value }) => {
    // We need to use { name, value } instead of event.target.name, etc
    // due to how Semantic UI handles events. More info here:
    // https://github.com/Semantic-Org/Semantic-UI-React/issues/638
    this.setState({ [name]: value });
  };

  submitForm = event => {
    this.props.postSighting(this.state.title, this.state.body);

    // Recall from above that this.state.Animal contains the animal id currently selected
    // so we can access it directly with this.state.Animal
    const animalId = this.state.Animal;

    // do stuff with animalId...
  };

  /**
   * If this is called, it will destroy the array of animals you have in your state and replace it with a gname
   * from one of the animals. You probably don't want this to happen.
   * Not sure what you are trying to do here, what do you use the return value for?
   * Also, this will return an array filled with 'undefined' since you don't return anything in the animals.map callback.
   */
  selectAnimal = () => {
    const mappedAnimals = this.state.animals.map(animal => {
      this.setState({ animal: animal.gname });
    });
    return mappedAnimals;
  };

  render() {
    return (
      //.......SKIP TO THE CODE THAT MATTERS

      <Form.Select
        label="Animal"
        name="Animal" // this is the name that gets passed to 'handlechange' as event.target.name
        onChange={this.handlechange}
        // selection: this isn't a valid prop for Form.Select and will be ignored regardless of value
        width={8}
        // value: we don't need to worry about this since Form.Select will handle it
        compact
        options={this.state.animals.map(animal => ({
          // return: was this a typo?
          name: animal.id,
          key: animal.id,
          value: animal.id, // This is the value that gets passed to 'handlechange' as event.target.value
          text: animal.gname
        }))}
      />
    );
  }
}

0
投票

经过大量的研究和@miyu的一些帮助,结果证明你的工作:

  <Form.Select
            fluid
            onChange={this.handleChange}
              placeholder='select animal'
              label="Animal"
              name="animal"

               width={8}
               selection
               options={this.state.animals.map(animal => ({
                 name: animal.gname,
                 key: animal.id,
                 value: animal.id,
                 text: animal.gname
               }))}
            />

你的handleChange应该是这样的:

handleChange = (e, { name, value }) => this.setState({ [name]: value })
© www.soinside.com 2019 - 2024. All rights reserved.