我不断看到使用 => 或 .bind(this) 的答案,但这些解决方案都没有奏效。
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});
}
解决方案:
_handleTextChange = (event) => {
var zip = event.nativeEvent.text;
this.setState({zip: zip});
alert('click');
}
原文由 Natus Drew 发布,翻译遵循 CC BY-SA 4.0 许可协议
当您使用 ES2015 类语法
extend
React.Component
时,您需要将动作处理程序绑定到您的类的上下文。试试这个:
onChange={e => _handleTextChange(e)}
一般来说,最好不要在
render
中使用箭头函数或bind
方法,因为它会在任何render
调用中生成该函数的新副本。将函数声明移动到class constructor
。在这种情况下,我个人更喜欢使用箭头函数作为类属性
它不是 ES2015 规范的一部分,但 babel stage-0 预设 支持这种语法
您可以在 本文 中阅读更多关于 React 中的上下文绑定的信息