(React)Uncaught TypeError:使用ref

时间:2018-04-17 18:02:15

标签: javascript reactjs

我试图在React中使用ref引用一个输入字段,但是我收到错误:“Uncaught TypeError:无法读取属性'this'of undefined”。然而,定义了ref。有没有理由为什么React无法在我的代码中找到ref?

    export default class ContractorSignUp extends Component {


  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();

    // Find the text field via the React ref
    const user = ReactDOM.this.refs.emailInput.value.trim();

    // Clear form
    ReactDOM.this.refs.emailInput.value = '';
  }


  render() {

    return (
            <form onSubmit={this.handleSubmit.bind(this)}>

              <input className="textinput" type="e-mail" placeholder="E-mail" ref="emailInput">
              </input>

          <button id="formsubmitbutton" onClick={this.handleSubmit.bind(this)}><span>Submit</span></button>

            </form>
                                    )
  }
};

1 个答案:

答案 0 :(得分:1)

只需删除ReactDOM部分:

// Find the text field via the React ref
const user = this.refs.emailInput.value.trim();

// Clear form
this.refs.emailInput.value = '';