A
A
Alexander2016-11-07 00:14:18
React
Alexander, 2016-11-07 00:14:18

Why doesn't it read through this.props.value?

Hello. I'm learning react using this tutorial and ran into a bit of a hitch at this point

var TestInput = React.createClass({
  getInitialState: function() {
    return {
      variable: 'Введите значение'
    };
  },
  changeVariable: function(e){
    this.setState({variable:e.target.value});  //   ВОТ ТУТ   
  },
  render: function() {
    var variable = this.state.variable;
    return (
      <input className='test-input' onChange={this.changeVariable} value={variable} />
    );
  }
});

Why this.setState({variable:e.target.value}); can't I use instead this.setState({variable:this.props.value}); ?
Only the loss of the this context comes to mind, but setState is also set via this

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artur Masloboev, 2016-11-07
@arthurmasl

In your case, this.props.value will look for the value parameter in the TestInput component, but there is none.

U
UsulPro, 2016-11-23
@UsulPro

I'm more familiar with ES6 class syntax.
From this point of view, the answer is precisely in the loss of context.
those. try for example onChange={this.changeVariable.bind(this)}
this.setState is defined in the parent class. Apparently this is the case.
In general, if you just started learning React, it might be worth switching to `class TestInput extends React.Component` (you are still using the jsx syntax). Here is a good guide

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question