首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >props.onChange(e.target.value)在material中返回对象而不是textField中的值

问props.onChange(e.target.value)在material中返回对象而不是textField中的值
EN

Stack Overflow用户
提问于 2021-04-24 11:28:02
回答 1查看 1K关注 0票数 2
代码语言:javascript
复制
  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)传递给组件时,它返回一个对象

input.MuiInputBase-input.MuiFilledInput-input,对象{ _reactName:"onChange",_targetInst: null,键入:“更改”,nativeEvent:输入,目标: currentTarget: input.MuiInputBase-input.MuiFilledInput-input,eventPhase: 3,气泡: true,可取消: false,timeStamp: 1398131,…}

代码语言:javascript
复制
<FormInput
    onChange={(value) => {
    console.log(value);
    }}
    label="Username"
    variant="filled"
></FormInput>

但是当我试图提醒这个值时,它写着“对象对象”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-24 11:35:47

看起来,onChange道具在TextField中被props.onChange覆盖。这是:

代码语言:javascript
复制
<TextField
  onChange={(e) => props.onChange(e.target.value)}
  InputProps={{ classes, disableUnderline: true }}
  {...props}
/>

可翻译为:

代码语言:javascript
复制
<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道具,然后按如下所示展开其余部分:

代码语言:javascript
复制
function FormInput({ onChange, ...rest }) {
  const classes = formInputStyles();

  return (
    <div>
       <TextField
         onChange={(e) => onChange(e.target.value)}
         InputProps={{ classes, disableUnderline: true }}
         {...rest}
       />
    </div>
  );
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67242289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档