Извлечение входных данных пользовательского интерфейса ReactJS - не определено - PullRequest
0 голосов
/ 09 ноября 2019

Попытка извлечь пользовательский текст из компонента Material UI inputbase

Я уверен, что делаю что-то не так, но не знаю, что.

import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import IconButton from '@material-ui/core/IconButton'
import InputBase from '@material-ui/core/InputBase'
import Paper from '@material-ui/core/Paper'
import SearchIcon from '@material-ui/icons/Search'

const useStyles = makeStyles(theme => ({}))

export default function CustomizedInputBase(props) {
  const [value, setValue] = React.useState()
  const classes = useStyles()

  const handleSearch = (event, newValue) => {
    setValue(newValue)
    props.click(value)
    console.log(newValue) // return undefined
    console.log(value)    // return undefined
  }

  return (
    <Paper className={classes.root}>
      <InputBase
        className={classes.input}
        value={value}
        placeholder="Szukaj Nazwisk"
        inputProps={{ 'aria-label': 'search google maps' }}
      />
      <IconButton className={classes.iconButton} aria-label="search" onClick={handleSearch}>
        <SearchIcon />
      </IconButton>
    </Paper>
  )
}

Есть идеи?

Ответы [ 2 ]

1 голос
/ 09 ноября 2019

Вы должны сделать исключение для неопределенного, как это.


    import React from 'react';
    import PropTypes from 'prop-types';
    import Paper from '@material-ui/core/Paper';
    import InputBase from '@material-ui/core/InputBase';
    import IconButton from '@material-ui/core/IconButton';
    import SearchIcon from '@material-ui/icons/Search';
    import makeStyles from '@material-ui/core/styles/makeStyles';

    const useStyles = makeStyles((theme) => ({
      root: {
        display: 'flex',
        alignItems: 'center',
        borderRadius: 30,
        width: 250,
        height: 40,
      },
      input: {
        marginLeft: theme.spacing(1),
        flex: 1,
      },
      inputField: {
        paddingLeft: theme.spacing(2),
        fontSize: 14,
      },
      iconButton: {
        padding: theme.spacing(1),
        marginLeft: theme.spacing(0.5),
        background: theme.palette.base[200],
        '& svg': {
          fill: theme.palette.base.white,
        },
      },
    }));

    function CustomSearchInput(props) {
      const classes = useStyles();
      const { disabled } = props;

      const onChange = (event) => {
        console.log(event.target.value);
      };

      return (
        <Paper className={classes.root}>
          <InputBase
            className={classes.input}
            placeholder="ID No."
            inputProps={{ 'aria-label': 'id no.', className: classes.inputField }}
            disabled={disabled}
            onChange={onChange}
          />
          <IconButton className={classes.iconButton} aria-label="search">
            <SearchIcon />
          </IconButton>
        </Paper>
      );
    }
0 голосов
/ 11 ноября 2019

См. Окончательный код решения:

export default function CustomizedInputBase(props) {
  const [value, setValue] = React.useState()
  const classes = useStyles()

  const handleSearch = (event) => { // changed the "handleSearch()" function
    props.click(value)
  }

  return (
    <Paper className={classes.root}>
      <InputBase
        className={classes.input}    //delete the 'value={value}'
        placeholder="Szukaj Nazwisk"
        inputProps={{ 'aria-label': 'search google maps' }}
        onChange={event=>{                                 //adding the onChange event
          setValue(event.target.value)
        }}
      />
      <IconButton className={classes.iconButton} aria-label="search" onClick={handleSearch}>
        <SearchIcon />
      </IconButton>
    </Paper>
  )
}

Необходимо удалить «значение = {значение}», в противном случае вы получите предупреждение консоли:

index.js:1375 Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: fb.me/react-controlled-components

Это может быть кому-то полезно:)

...