【发布时间】:2018-02-07 12:17:06
【问题描述】:
我在 react 中工作,我提供了自定义输入。自定义输入通过提供 myRef 作为 react 的 ref 的道具在某些组件中使用。但是所有过程都很好,但它在控制台中显示未定义的值。
自定义输入
class CustomInput extends React.Component {
render() {
const { classes, formControlProps, labelText, id, labelProps,inputRef, inputProps, error, success } = this.props;
return (
<FormControl {...formControlProps} className={formControlProps.className + " " + classes.formControl}>
{labelText !== undefined ? (<InputLabel
classes={{
root: classes.labelRoot + (error ? " " + classes.labelRootError:success ? " " + classes.labelRootSuccess:""),
}}
htmlFor={id}
{...labelProps}
>
{labelText}
</InputLabel>):null}
<Input
classes={{
root: (labelText !== undefined ? "":classes.marginTop),
disabled: classes.disabled,
underline: classes.underline,
inkbar: (error ? classes.inkbarError:success ? classes.inkbarSuccess:classes.inkbar),
}}
id={id}
ref={inputRef} //Here ref props is map with inputRef
{...inputProps}
/>
{error ? <Clear className={classes.feedback + " " + classes.labelRootError}/>:success ? <Check className={classes.feedback + " " + classes.labelRootSuccess}/>:null}
</FormControl>
);
}
}
在其他组件中使用自定义输入
handleSubmit(event) {
event.preventDefault();
console.log(this.email.value); //show undefined in console
}
<form onSubmit={this.handleSubmit.bind(this)}>
<CustomInput
labelText="Email"
id="email"
inputRef={(input) => {this.email = input}} // provided inputRef Prop
formControlProps={{
fullWidth: true
}}
inputProps ={{
type:"email",
}}
/>
</ItemGrid>
</form>
【问题讨论】:
-
你在构造函数中绑定
handleSubmit函数吗 -
没有我在构造函数中绑定了,但是为什么我们需要在构造函数中绑定
-
在表单标签中绑定没关系。
this.email在console.log中给出了什么` -
this.email.value 在控制台中提供未定义
标签: javascript reactjs material-ui