javascript - Prop 处理程序不能一致工作?

标签 javascript reactjs react-native

我正在开发 RN 应用程序,但遇到了一个问题:由于子组件中发生的事件,我尝试更改组件的状态,但得到的结果不一致。

var app = React.createClass({
  render: function() {
    return (
      <MainLogin onLogin={this.onLogin} />
    );
  },
  onLogin: function() {
    this.setState({isLoggedIn: true});
  }
});

class MainLogin extends Component {
  render() {
    return(
      <Login changeSomething={this.changeSomething} onLogin={this.props.onLogin}/>
    );
  }

  changeSomething() {
    this.setState({something: true});
  }
}

class Login extends Component {
  constructor(props) {
    super(props);
  }

  loginPressed() {
    this.props.onLogin(); //This works
  }

  changeSomething() {
    this.props.changeSomething(); //This doesn't work
  }

  render() {
    return (
      <View style={{flex: 1}}>
        <Button onPress={this.changeSomething.bind(this)}>Change Something</Button>
        <Button onPress={this.loginPressed.bind(this)}>Login</Button>
      </View>
    );
  }
}

onLogin 函数运行完美,并且能够设置 Grandparent 组件的状态,而 changeSomething 函数失败(this.setState 不是函数)。

有什么建议吗?

最佳答案

您应该绑定(bind) ES6 类中的组件方法。React.createClass 自动执行此操作,但您的第二个和第三个组件是 ES6 类的子类。这是一个explanation官方网站上有相关内容。

关于javascript - Prop 处理程序不能一致工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35584797/

相关文章:

ios - Xcode 更新后库停止工作。 react native 0.62.2

javascript - prettyPhoto 不工作 - 错误 : Not a Function

样式不起作用的 Javascript 函数参数

javascript - 什么时候使用 .val() 与 .innerHTML?

javascript - Mobx 状态树能否导致 "race conditions"/仅适用于 setTimeout?

javascript - 在 URL 前缀下将 React 应用程序添加到 Flask

javascript - React Native : Error :"Cannot read property ' name' of undefined,“虽然包含名称的对象不是未定义的

javascript - 您可以在 SQL SELECT 查询中使用从 AJAX 发布的数据吗

javascript - 简单的 react 过滤

javascript - 在react-native中找不到变量