【问题标题】:prop handlers not working consistently?道具处理程序无法始终如一地工作?
【发布时间】:2016-02-23 17:57:14
【问题描述】:

我正在开发一个 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 函数运行完美,能够设置祖父组件的状态,而 changeSomething 函数失败(this.setState 不是函数)。

有什么建议吗?

【问题讨论】:

  • 闻起来像绑定问题..尝试:changeSomething={this.changeSomething.bind(this)}
  • 嗯,这立即奏效了。谢谢你。你知道为什么这会是一个问题而不是另一个问题吗?

标签: javascript reactjs react-native


【解决方案1】:

您应该在 ES6 类中绑定组件方法。React.createClass 会自动这样做,但是您的第二个和第三个组件是 ES6 类的子类。这是官方网站上的explanation。

【讨论】:

  • 啊,好吧。这就解释了。谢谢。
猜你喜欢
  • 2013-04-16
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多