从一个组件到另一个组件反应传递值

时间:2019-06-17 15:09:43

标签: reactjs

我有一个名为Auto Complete的组件,在这里我使用material-ui DownShift选择多个状态。并在我的注册表单组件中调用此组件,但是如何在注册组件中获取选定的状态详细信息。

任何帮助表示赞赏。

注册表单组件

import AutoComplete from './autocomplete.js'
.....
 <GridContainer>
                <GridItem xs={12} sm={12} md={12}>

                    <AutoComplete/>
                    </GridItem>
                    <GridItem xs={12} sm={12} md={12}>
                            <CustomInput
                                labelText="Districts Covered"
                                id="usr_org_DistConvered"
                                formControlProps={{
                                    fullWidth: true
                                }}
                                inputProps={{
                                    type: "text",
                                    onChange: (event) => this.handleChange(event),
                                    error: (!!this.state.usr_org_DistConveredError),
                                    helperText: (this.state.usr_org_DistConveredError),
                                }}
                            />

                    </GridItem>
                </GridContainer>

autoComplete.js

import React from "react";
import PropTypes from "prop-types";
import deburr from "lodash/deburr";
const suggestions = statedist.states;

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

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

  return (
    <MenuItem
      {...itemProps}
      key={suggestion.state}
      selected={isHighlighted}
      component="div"
      style={{
        fontWeight: isSelected ? 500 : 400
      }}
    >
      {suggestion.state}
    </MenuItem>
  );
}
renderSuggestion.propTypes = {
  highlightedIndex: PropTypes.number,
  index: PropTypes.number,
  itemProps: PropTypes.object,
  selectedItem: PropTypes.string,
  suggestion: PropTypes.shape({ label: PropTypes.string }).isRequired
};

function getSuggestions(value, { showEmpty = false } = {}) {
  console.log("click");
  const inputValue = deburr(value.trim()).toLowerCase();
  const inputLength = inputValue.length;
  let count = 0;

  return inputLength === 0 && !showEmpty
    ? []
    : suggestions.filter(suggestion => {
        const keep =
          count < 5 &&
          suggestion.state.slice(0, inputLength).toLowerCase() === inputValue;

        if (keep) {
          count += 1;
        }

        return keep;
      });
}

function DownshiftMultiple(props) {
  const { classes } = props;
  const [inputValue, setInputValue] = React.useState("");
  const [selectedItem, setSelectedItem] = React.useState([]);

  function handleKeyDown(event) {
    if (
      selectedItem.length &&
      !inputValue.length &&
      event.key === "Backspace"
    ) {
      setSelectedItem(selectedItem.slice(0, selectedItem.length - 1));
    }
  }

  function handleInputChange(event) {
    setInputValue(event.target.value);
  }

  function handleChange(item) {
    let newSelectedItem = [...selectedItem];
    if (newSelectedItem.indexOf(item) === -1) {
      newSelectedItem = [...newSelectedItem, item];
    }
    setInputValue("");
    setSelectedItem(newSelectedItem);
  }

  const handleDelete = item => () => {
    const newSelectedItem = [...selectedItem];
    newSelectedItem.splice(newSelectedItem.indexOf(item), 1);
    setSelectedItem(newSelectedItem);
  };

  return (
    <Downshift
      id="downshift-multiple"
      inputValue={inputValue}
      onChange={handleChange}
      selectedItem={selectedItem}
    >
      {({
        getInputProps,
        getItemProps,
        getLabelProps,
        isOpen,
        inputValue: inputValue2,
        selectedItem: selectedItem2,
        highlightedIndex
      }) => {
        const { onBlur, onChange, onFocus, ...inputProps } = getInputProps({
          onKeyDown: handleKeyDown,
          // placeholder: "Select multiple State"
        });

        return (
          <div className={classes.container}>
            {renderInput({
              fullWidth: true,
              classes,
              // label: "States",
              InputLabelProps: getLabelProps(),
              InputProps: {
                startAdornment: selectedItem.map(item => (
                  <Chip
                    key={item}
                    tabIndex={-1}
                    label={item}
                    className={classes.chip}
                    onDelete={handleDelete(item)}
                  />
                )),
                onBlur,
                onChange: event => {
                  handleInputChange(event);
                  onChange(event);
                },
                onFocus
              },
              inputProps
            })}

            {isOpen ? (
              <Paper className={classes.paper} square>
                {getSuggestions(inputValue2).map((suggestion, index) =>
                  renderSuggestion({
                    suggestion,
                    index,
                    itemProps: getItemProps({ item: suggestion.state }),
                    highlightedIndex,
                    selectedItem: selectedItem2
                  })
                )}
              </Paper>
            ) : null}
          </div>
        );
      }}
    </Downshift>
  );
}

DownshiftMultiple.propTypes = {
  classes: PropTypes.object.isRequired
};



 function IntegrationDownshift({ ...props }) {
  const classes = props;

  return (
    <div className={classes.root}>
      <DownshiftMultiple classes={classes} />
    </div>
  );
}
export default withStyles(customInputStyle)(IntegrationDownshift)

1 个答案:

答案 0 :(得分:1)

React中共有3种共享状态的方式:Context Api,第三方状态管理器(Redux,Flux,MobX)和prop钻探。您可能想研究使用Context Api,因为它可能是解决问题的最简单快捷的解决方案。