javascript - 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] ”的值时
解决方案
看起来 中的onChange
道具TextField
被props.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>
);
}
推荐阅读
- java - 如何通过 MySql DB 上的 Spring Jdbc 模板在获取列表中应用限制和偏移量
- php - Eloquent 在重新调整数据之前修改数据
- python - 如何在 Django 表单中创建一个用户无法编辑的只读字段?
- r - 暂时忽略 R 中的某些库
- ckeditor - CKEditor 在保存时正在更改我的 SRC 或 Href
- string - sqlite instr 函数在某些情况下不起作用
- java - 如何在 onActivityResult 之后修复 JNI 代码中的 Android 崩溃?
- opencv - 如果我使用裁剪对象或全帧来训练级联分类器,有什么区别吗?
- java - 检索 Firebase 对象空指针异常
- c# - 如何在 VS 中正确处理引用