最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJs print value of input field - Stack Overflow

programmeradmin4浏览0评论

I'm trying to print instantly my input value in the render function.

In the documentation of the concept of state and lifecycle in a React ponent, I see the use of a constructor with a super(props) as well as this.state.

I get the error below when trying same;

Uncaught TypeError: Cannot read property 'state' of undefined

Below is my code;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: ''
    };
  };

  handleChange(event) {
    this.setState({
      text: event.target.value
    });
  };

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.text}.</h2>
        <input type="text" onKeyUp={this.handleChange} />
      </div>
    );
  }
}

How can I fix it?

I'm trying to print instantly my input value in the render function.

In the documentation of the concept of state and lifecycle in a React ponent, I see the use of a constructor with a super(props) as well as this.state.

I get the error below when trying same;

Uncaught TypeError: Cannot read property 'state' of undefined

Below is my code;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: ''
    };
  };

  handleChange(event) {
    this.setState({
      text: event.target.value
    });
  };

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.text}.</h2>
        <input type="text" onKeyUp={this.handleChange} />
      </div>
    );
  }
}

How can I fix it?

Share Improve this question edited Jan 22, 2020 at 6:55 nyedidikeke 7,6788 gold badges47 silver badges63 bronze badges asked Oct 24, 2016 at 17:15 SireiniSireini 4,26213 gold badges55 silver badges96 bronze badges 1
  • 2 this.handleChange=this.handleChange.bind(this) in constructor – Burak Karasoy Commented Oct 24, 2016 at 17:28
Add a ment  | 

4 Answers 4

Reset to default 3

when you call a function like that, it is called by the window, not by your react object.

To make the function be bound to your react object (and have the ability to use the setState method, you need to use this:

onKeyUp={this.handleChange.bind(this)}

this will bind it to your react object :)

You have to bind this to your event handler like this:

<input type="text" onKeyUp={this.handleChange.bind(this)} />

Working Example: https://codepen.io/shanedaugherty/pen/ALwAzL

this.handleChange = this.handleChange.bind(this); You can bind it like this in constructor and it will work, as you have to bind this to your react function.

You use value as an attribute.

value={this.state.text}

OR

发布评论

评论列表(0)

  1. 暂无评论