this.setState 未定义 [英] this.setState is undefined
问题描述
我一直看到答案说使用 => 或 .bind(this) 但这些解决方案都不起作用.
import React, { Component } from 'react';import { View, Text, TextInput, StyleSheet } from 'react-native';导出默认类 MyWeatherApp 扩展组件 {构造函数(道具){超级(道具);this.state = {};}getInitialState() {返回 {压缩: '',预测:空,};}_handleTextChange(事件){var zip = event.nativeEvent.text;this.setState({zip: zip});}
解决方案:
_handleTextChange = (event) =>{var zip = event.nativeEvent.text;this.setState({zip: zip});警报('点击');}
当您使用 ES2015 类语法extend
React.Component
时,您需要将动作处理程序绑定到你的班级背景.
试试这个:onChange={e =>_handleTextChange(e)}
通常,最好不要在 render
中使用箭头函数或 bind
方法,因为它会在任何 render
上生成函数的新副本称呼.将函数声明移至类构造函数
.
我个人更喜欢在这种情况下使用箭头函数作为类属性
class MyClass 扩展 React.Component {handleClick = () =>{//你的逻辑};使成为() {返回 (<button onClick={this.handleClick}>点击我</button>);}}
它不是 ES2015 规范的一部分,但 babel stage-0 preset 支持这种语法>
您可以在这篇文章
I keep seeing answers that say to use => or .bind(this) but neither of those solutions worked.
import React, { Component } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';
export default class MyWeatherApp extends Component {
constructor(props) {
super(props);
this.state = {};
}
getInitialState() {
return {
zip: '',
forecast: null,
};
}
_handleTextChange(event) {
var zip = event.nativeEvent.text;
this.setState({zip: zip});
}
Solution:
_handleTextChange = (event) => {
var zip = event.nativeEvent.text;
this.setState({zip: zip});
alert('click');
}
When you extend
React.Component
with ES2015 class syntax you need to bind your action handlers to a context of your class.
Try this: onChange={e => _handleTextChange(e)}
Generally, it's better not to use arrow functions or bind
methods inside render
as it generates a new copy of the function on any render
call. Move function declaration to the class constructor
.
I personally prefer to use arrow functions as class properties in this case
class MyClass extends React.Component {
handleClick = () => {
// your logic
};
render() {
return (
<button onClick={this.handleClick}>Click me</button>
);
}
}
It's not a part of ES2015 specification but babel stage-0 preset supports this syntax
You can read more about context binding in React in this article
这篇关于this.setState 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!