Unable to read property 'state' of null

I have an input and a button

<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.handleSentence}></button>

I linked both functions in the constructor.

onChange(e) {this.setState({sentence: e.target.value});}

handleSentence(e) {console.log('string -->',this.state.sentence)}

in function handleSentence logreturns Cannot read property 'state' of null.

but in render(let{sentence}=this.state)returns the correct value, and also I see what I enter in the input

Here is the constructor:

class SentenceForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sentence: '',
            splitedSentenceArray:[]
        }
        this.onChange = this.onChange.bind(this);
        this.onClick = this.handleSentence.bind(this);
    }
+4
source share
2 answers

It should look like this:

<input className="form-control" value={this.state.sentence} onChange={this.onChange}/>
<button type="button" onClick={this.onClick}></button>

You have bound the method handleSentencebefore this.onClick. This was wrong.

+4
source

. , . handleSentence , , , , , .

class SentenceForm extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sentence: '',
            splitedSentenceArray:[]
        }
        this.onChange = this.onChange.bind(this);
        this.handleSentence = this.handleSentence.bind(this);
    }
+5

Source: https://habr.com/ru/post/1662863/


All Articles