简体   繁体   English

无法使用React JS中的引用检索材料UI的输入字段

[英]Unable to retrieve the input field of material UI using refs in react js

I am developing a Web application using React JS + Material UI core. 我正在使用React JS + Material UI核心开发一个Web应用程序。 Now, I am building a form with the material ui control. 现在,我正在使用材料ui控件构建表单。 Now, I am trying to retrieve the input field value (TextField) using refs of React. 现在,我试图使用React的引用来检索输入字段值(TextField)。 It is always saying undefined. 总是说不确定。

This is my component 这是我的组成部分

class CreateEventComponent extends React.Component{

    constructor(props)
    {
        super(props)


    }


    submitCreateEventForm(e)
    {
        e.preventDefault();
        alert(this.refs.name.input.value)
    }

    render()
    {
        return (
            <MuiThemeProvider>
            <div className={scss['page-container']}>
            <Grid
            spacing={16}
            container>
                <Grid item md={12}>
                    <Card>
                    <CardContent>
                        <form onSubmit={this.submitCreateEventForm.bind(this)}>
                        <div>
                            <TextField
                            ref="name"
                            className={scss['form-control']}
                            name="name"
                            label="Name" />
                        </div>

                        <div>
                        <Grid>
                        <Button type="submit" color="primary" variant="raised">Save</Button>
                        </Grid>
                        </div>
                        </form>
                    </CardContent>
                    </Card>
                </Grid>
            </Grid>
            </div>
            </MuiThemeProvider>
        )
    }

}

function mapStateToProps(state)
{
    return {

    };
}

function matchDispatchToProps(dispatch)
{
    return bindActionCreators({

    }, dispatch);
}

const enhance = compose(withWidth(), withStyles(themeStyles, { withTheme: true }), connect(mapStateToProps, matchDispatchToProps))
export default enhance(CreateEventComponent);

As you can see, when form submits, I am trying to alert the name input field using refs. 如您所见,当表单提交时,我正在尝试使用refs来提醒名称输入字段。 But it is always showing "undefined". 但它始终显示“未定义”。 I tried using this to fetch the value of TextField. 我尝试使用它来获取TextField的值。

alert(this.refs.name.value)

It throws error saying name is undefined. 抛出错误,提示名称未定义。 So, how can I fetch the value of TextField using Ref? 因此,如何使用Ref获取TextField的值?

I used this way as well. 我也用这种方式。

I create ref in the constructor 我在构造函数中创建ref

 constructor(props)
    {
        super(props)

        this.nameRef = React.createRef();
    }

Then set the ref for the TextField 然后设置TextField的引用

<TextField
                            ref={this.nameRef}
                            className={scss['form-control']}
                            name="name"
                            label="Name" />

Then retrieve the values in this ways. 然后以这种方式检索值。

this.nameRef.value
this.nameRef.input.value

It is giving me the same error as well. 这也给了我同样的错误。

Original Answer 原始答案

You need to create a ref in your constructor. 您需要在构造函数中创建一个ref

From the docs : 文档

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef(); // create a ref
    }

    render() {
        return <div ref={this.myRef} />;
    }
}

Updated Answer 更新的答案

According to Material UI's documentation , you need to pass in a callback to the inputRef prop on your <TextField /> . 根据Material UI的文档 ,您需要将回调传递给<TextField />上的inputRef

So, in addition to the original answer, try this as well: 因此,除了原始答案外,还请尝试以下操作:

<TextField
    inputRef={e => this.nameRef = e}
    className={scss['form-control']}
    name="name"
    label="Name" />

For me, this solves the problem: 对我来说,这可以解决问题:

<TextField
  ref={this.nameRef}
  onChange={e => {
    this.nameRef.current.value = e.target.value;
  }}
  className={scss['form-control']}
  name="name"
  label="Name" />

if you are using a stateless functional component with material ui then you can use react hooks. 如果您正在使用带有材料ui的无状态功能组件,则可以使用react挂钩。

import React, { useState, useRef } from "react";

let MyComponent = (props) => {

  let textInput = useRef(null);

  return (
    <div>
      <Button
        onClick={() => {
          setTimeout(() => {
            textInput.current.focus();
            textInput.current.click();
            textInput.current.value="myname";
            console.log(textInput.current.value);
          }, 100);
        }}
      >
        Focus TextField
      </Button>
      <TextField
        fullWidth
        required
        inputRef={textInput}
        name="firstName"
        type="text"
        placeholder="Enter Your First Name"
        label="First Name"
      />
    </div>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM