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});
}

解决方案:

_handleTextChange = (event) => {
  var zip = event.nativeEvent.text;
  this.setState({zip: zip});
  alert('click');
}

推荐答案

使用ES2015类语法时,需要将动作处理程序绑定到类的上下文.

试试这个:onChange={e => _handleTextChange(e)}

一般来说,最好不要在render中使用箭头函数或bind个方法,因为它会在任何render调用中生成函数的新副本.将函数声明移到class constructor.

我个人更喜欢在这种情况下使用箭头函数作为类属性

class MyClass extends React.Component {

  handleClick = () => {
    // your logic
  };

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}

它不是ES2015规范的一部分,但babel stage-0 preset支持这种语法

您可以在React in this article中阅读有关上下文绑定的更多信息

Reactjs相关问答推荐

过滤对象数组并通过迭代对象数组将属性放入新数组

react 派生状态未正确更新

避风港访问端口以包含Reaction应用程序

PWA:注册事件侦听器不会被触发

Next.js `getLayout` 函数没有被调用

Mui DataGrid 在第二页和前一页上显示项目时出现问题

如何在next.js 13中仅在主页导航栏上隐藏组件?

React Native 背景动画反转

FlatList 不在 React Native 中呈现项目

如何在 React map 函数循环中使用
标签

MUI - ButtonGroup fullWidth 条件屏幕大小不起作用?

React JS:如何判断用户使用的是浏览器 url 还是桌面 electron

如何向 surveyjs 调查添加多个结尾?

如何解决在 react.js 中找不到模块错误

为什么此代码中的 useState 不更新(文本更新但 id 不更新)?

如何使用react 路由将 url 参数限制为一组特定的值?

如何使用 UseState 正确测试组件

设置 Material UI 表格默认排序

Context Api React 的问题

可以'读取未定义的属性(读取'路径')