- When we bind a method to a DOM element, for example:
<input type="text" ref="myinput" accept = "image/*" onChange = {this.selectFile} />
- Uncaught TypeError: Cannot read property ‘refs’ of null or undefind
chestnut
import React from 'react';
import $ from 'jquery'
import '.. /app.scss';
export default class MyForm extends React.Component {
submitHandler (event) {
event.preventDefault();
console.log(this.refs.helloTo);
var helloTo = this.refs.helloTo.value;
alert(helloTo);
}
render () {
return (
<form onSubmit={this.submitHandler}>
<input ref='helloTo' type='text' defaultValue='Hello World! ' />
<button type='submit'>Speak</button>
</form>)}}Copy the code
Bind ={this.handleclick};};};};};};};};};};};}; The solution is to bind(this) when the function is called, so that this refers to the currently instantiated object regardless of how the event handler is passed.
To solve
- There are four solutions
- In ES6, you can bind an instance of the current component (or class) directly to a function in a constructor.
- Bind this to the method call as follows:
<input type="file" ref="myinput" accept = "image/*" onChange = {this.selectFile.bind(this)} />
- At the end of the method, bind (this) :
SubmitHandler () {console.log (1The bind ()}this)
Copy the code
- Use the ES6 arrow function
myfn = () =>{ console.log(this.refs.can) }
Recommended to use the arrow function, because recently changed to react, did not see much to cli to fight, encountered some small problems recorded here