【问题标题】:React ref gives undefine in custom input of material uiReact ref 在材料 ui 的自定义输入中给出 undefine
【发布时间】: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


【解决方案1】:

我将您的代码放入 CodeSandbox 编辑器中,它似乎工作正常。 当我按下回车键(提交表单)时,我会在控制台中收到电子邮件。如果电子邮件有效。

你能看看,也许更好地向我们解释一下问题是什么?可能我没听懂你在说什么。

LE:ref 适用于原生 input 元素。对于来自react-ui-next 的自定义Input,您应该使用inputRef

【讨论】:

  • 我正在使用 Material-ui 和 react。其中 Input 和 FormControl 是 material-ui 的组件。
  • 我已经使用react-ui-next 更新了 CodeSandbox 的工作示例。您应该在来自react-ui-nextInput 组件上使用inputRef 而不是ref
猜你喜欢
  • 2018-07-21
  • 2020-12-20
  • 2020-04-26
  • 2020-01-25
  • 2020-05-07
  • 2020-09-02
  • 2020-07-27
  • 2016-11-21
  • 2022-11-29
相关资源
最近更新 更多