Реагировать материал-интерфейс на JS автозаполнение выбор элемента возврат в obj в функции

enter image description here

Используя материал-UI и пониженную, я модифицировал компонент таким образом, что его можно есть даже при однократном отборе следующий опыт этого чипа, чтобы лучше понять, что выбор был удачным.

Даже глядя на документацию, я не могу выяснить, как получить выбранный товар мне в качестве объекта, но на данный момент мне удалось сделать этикетку обратно ко мне и это не то, что я хочу.

Я хотел бы убедиться в том, что когда пользователь выбирает элемент из списка, все сведения о пользователе возвращается ко мне, т. е. все предметы, которые.

На рисунке показано, что код в настоящее время.

Кто-то может дать мне руку.

Ссылка: codesandbox

Код Дома:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import IntegrationDownshift from "./IntegrationDownshift";

export default class Home extends Component {
  constructor() {
    super();
    this.state = {
      userSelect: {}
    };
  }
  onSearch = q => {
    console.log("onSearchHome", q);
  };
  render() {
    const { userSelect } = this.state;
    const suggestions = [
      {
        name: "Russell",
        surname: "Tran",
        address: "347 Lawn Court, Homeland, Wyoming, 8885",
        streetNumber: 39,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Ophelia",
        surname: "Bowen",
        address: "985 Hoyts Lane, Takilma, California, 3649",
        streetNumber: 27,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Williams",
        surname: "Cervantes",
        address: "872 Hendrix Street, Nile, Kansas, 2594",
        streetNumber: 32,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Case",
        surname: "Brewer",
        address: "854 Nolans Lane, Kraemer, New Mexico, 8773",
        streetNumber: 27,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Ryan",
        surname: "Williams",
        address: "470 Holly Street, Bellfountain, Illinois, 137",
        streetNumber: 38,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Tammie",
        surname: "Holloway",
        address: "185 Willow Place, Brandywine, Northern Mariana Islands, 5066",
        streetNumber: 26,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Celina",
        surname: "Warner",
        address: "890 Woods Place, Dixonville, Washington, 9492",
        streetNumber: 27,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Gibson",
        surname: "Beasley",
        address: "723 Strickland Avenue, Statenville, Idaho, 9160",
        streetNumber: 27,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Faulkner",
        surname: "Webster",
        address: "679 Leonora Court, Caberfae, Iowa, 3296",
        streetNumber: 23,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Luna",
        surname: "Sampson",
        address: "782 Mermaid Avenue, Newry, Virgin Islands, 4055",
        streetNumber: 24,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Virginia",
        surname: "Flynn",
        address: "227 Sharon Street, Limestone, North Carolina, 8294",
        streetNumber: 31,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Alba",
        surname: "Dillon",
        address: "108 Debevoise Street, Wolcott, New Hampshire, 2718",
        streetNumber: 24,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Jeanette",
        surname: "Cruz",
        address: "970 Albemarle Road, Outlook, Oregon, 636",
        streetNumber: 25,
        password: 123456,
        email: "[email protected]",
        role: "user"
      },
      {
        name: "Alb",
        surname: "Donovan",
        address: "927 Suydam Place, Canby, American Samoa, 5845",
        streetNumber: 30,
        password: 123456,
        email: "[email protected]",
        role: "user"
      }
    ].map(suggestion => ({
      //value: suggestion.name,
      //label: suggestion.email,
      name: suggestion.name,
      surname: suggestion.surname,
      andress: suggestion.andress,
      email: suggestion.email
    }));
    return (
      <>
        Name: [{userSelect && userSelect.name}]<br />
        <br />
        Surname: [{userSelect && userSelect.surname}]<br />
        <br />
        Email: [{userSelect && userSelect.email}]<br />
        <br />
        <IntegrationDownshift
          options={suggestions}
          onSearch={this.onSearch}
          onChange={userSelect => this.setState({ userSelect })}
          //selectedItem={userSelect}
        />
      </>
    );
  }
}

ReactDOM.render(<Home />, document.querySelector("#root"));

Код Компонента:

import React from "react";
import PropTypes from "prop-types";
import deburr from "lodash/deburr";
import Downshift from "downshift";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";
import MenuItem from "@material-ui/core/MenuItem";
import Chip from "@material-ui/core/Chip";
import "./App.css";

function renderInput(inputProps) {
  const { InputProps, classes, ref, ...other } = inputProps;
  return (
    <TextField
      InputProps={{
        inputRef: ref,
        classes: {
          root: classes.inputRoot,
          input: classes.inputInput
        },
        ...InputProps
      }}
      {...other}
      value=""
    />
  );
}

renderInput.propTypes = {
  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object.isRequired,
  InputProps: PropTypes.object
};

function renderSuggestion(suggestionProps) {
  const {
    suggestion,
    index,
    itemProps,
    highlightedIndex,
    selectedItem
  } = suggestionProps;
  const isHighlighted = highlightedIndex === index;
  const isSelected = (selectedItem || "").indexOf(suggestion.label) > -1;

  return (
    <MenuItem
      {...itemProps}
      key={suggestion.email}
      selected={isHighlighted}
      component="div"
      style={{
        fontWeight: isSelected ? 500 : 400
      }}
    >
      {suggestion.name} {suggestion.surname}
    </MenuItem>
  );
}

renderSuggestion.propTypes = {
  highlightedIndex: PropTypes.oneOfType([
    PropTypes.oneOf([null]),
    PropTypes.number
  ]).isRequired,
  index: PropTypes.number.isRequired,
  itemProps: PropTypes.object.isRequired,
  selectedItem: PropTypes.string.isRequired,
  suggestion: PropTypes.shape({
    label: PropTypes.string.isRequired
  }).isRequired
};

function getSuggestions(value, { options, showEmpty = false } = {}) {
  const inputValue = deburr(value.trim()).toLowerCase();
  const inputLength = inputValue.length;
  //let count = 0;

  let el = inputLength === 0 && !showEmpty ? [] : options;
  /*.filter(suggestion => {
        const keep =
          count < 5 &&
          suggestion.label.slice(0, inputLength).toLowerCase() === inputValue;

        if (keep) {
          count += 1;
        }

        return keep;
      });*/

  //console.log(el);

  return el;
}

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    height: 250
  },
  container: {
    flexGrow: 1,
    position: "relative"
  },
  paper: {
    position: "absolute",
    zIndex: 1,
    marginTop: theme.spacing(1),
    left: 0,
    right: 0
  },
  chip: {
    margin: theme.spacing(0.5, 0.25)
  },
  inputRoot: {
    flexWrap: "wrap"
  },
  inputInput: {
    width: "auto",
    flexGrow: 1
  },
  divider: {
    height: theme.spacing(2)
  }
}));

export default function IntegrationDownshift({
  options,
  onSearch,
  onChange,
  selectedItem
}) {
  //console.log("selectedItem",selectedItem)
  //let item = selectedItem ? [selectedItem.name] : undefined;
  //console.log("Myoptions", options)
  const classes = useStyles();

  /*const handleDelete = item => () => {
    console.log("delete", item);
  };*/

  function handleInputChange(event) {
    console.log("handleInputChangeINT", event.target.value);
    onSearch(event.target.value);
  }

  function handleChange(event) {
    console.log("handleChangeINT", event);
    if (event !== null) {
      let email = event.split("(")[1].replace(")", "");
      onChange({ name: "ReturnName", surname: "ReturnSurname", email });
    } else onChange({});
  }

  return (
    <div className={classes.root}>
      <Downshift
        id="downshift-options"
        onChange={handleChange}
        //selectedItem={item}
      >
        {({
          clearSelection,
          getInputProps,
          getItemProps,
          getLabelProps,
          getMenuProps,
          highlightedIndex,
          inputValue,
          isOpen,
          openMenu,
          selectedItem
        }) => {
          const { onBlur, onChange, onFocus, ...inputProps } = getInputProps({
            onChange: event => {
              console.log("onChangeDINT", event.target.value);
              if (event.target.value === "") {
                clearSelection();
              }
            },
            onFocus: openMenu,
            placeholder: "Cerca user"
          });

          return (
            <div className={classes.container}>
              {renderInput({
                fullWidth: true,
                classes,
                label: "User",
                InputLabelProps: getLabelProps({ shrink: true }),
                //InputProps: { onBlur, onChange, onFocus },
                InputProps: {
                  endAdornment: selectedItem !== null && (
                    <Chip
                      key={1}
                      tabIndex={-1}
                      label={selectedItem}
                      className={classes.chip}
                      onDelete={() => clearSelection()}
                    />
                  ),
                  onBlur,
                  onChange: event => {
                    handleInputChange(event);
                    onChange(event);
                  },
                  onFocus
                },
                inputProps
              })}

              <div {...getMenuProps()}>
                {isOpen ? (
                  <Paper className={classes.paper} square>
                    {getSuggestions(inputValue, {
                      options,
                      showEmpty: false
                    }).map((suggestion, index) =>
                      renderSuggestion({
                        suggestion,
                        index,
                        itemProps: getItemProps({
                          item:
                            suggestion.name +
                            " " +
                            suggestion.surname +
                            " (" +
                            suggestion.email +
                            ")"
                        }),
                        highlightedIndex,
                        selectedItem
                      })
                    )}
                    {getSuggestions(inputValue, { options, showEmpty: true })
                      .length === 0 && (
                      <MenuItem
                        key={11}
                        selected={false}
                        component="div"
                        style={{
                          fontWeight: false ? 500 : 400
                        }}
                      >
                        Nessun elemento è stato trovato.
                      </MenuItem>
                    )}
                  </Paper>
                ) : null}
              </div>
            </div>
          );
        }}
      </Downshift>
    </div>
  );
}
0
2019-09-18 12:11:04
источник
0 ответов

Посмотрите другие вопросы по меткам