首页 > 解决方案 > props.onChange(e.target.value) 在材质ui中的textField中返回一个对象而不是一个值

问题描述

  function FormInput(props) {
    const classes = formInputStyles();
    return (
      <div>
        <TextField
        onChange={(e) => props.onChange(e.target.value)}
          InputProps={{ classes, disableUnderline: true }}
          {...props}
        />
      </div>
    );
  }

当试图将 (e.target.value) 传递给组件时,它返回一个对象

Object { _reactName: "onChange", _targetInst: null, type: "change", nativeEvent: input, target: input.MuiInputBase-input.MuiFilledInput-input, currentTarget: input.MuiInputBase-input.MuiFilledInput-input, eventPhase: 3,气泡:真,可取消:假,时间戳:1398131,...}

<FormInput
    onChange={(value) => {
    console.log(value);
    }}
    label="Username"
    variant="filled"
></FormInput>

但是当我尝试提醒它说“ [object Object] ”的值时

标签: javascriptreactjsmaterial-ui

解决方案


看起来 中的onChange道具TextFieldprops.onChange. 这:

<TextField
  onChange={(e) => props.onChange(e.target.value)}
  InputProps={{ classes, disableUnderline: true }}
  {...props}
/>

可以翻译成:

<TextField
  onChange={(e) => props.onChange(e.target.value)}
  InputProps={{ classes, disableUnderline: true }}
  {...}
  // because you're spreading all props. props.onChange receives e (object)
  // instead of e.target.value
  onChange={props.onChange}
/>

解决方案是提取onChange道具并散布其余部分,如下所示:

function FormInput({ onChange, ...rest }) {
  const classes = formInputStyles();

  return (
    <div>
       <TextField
         onChange={(e) => onChange(e.target.value)}
         InputProps={{ classes, disableUnderline: true }}
         {...rest}
       />
    </div>
  );
}

推荐阅读