首页 > 解决方案 > 如何在 react 的 render 方法中调用方法

问题描述

我遇到了 React nooob 问题。问题是我需要在方法中调用一个名为 namexxxrender方法,但我不知道如何。

这是方法:

xxx() {
    return (
        this.state.dataLoadedQuote &&
        <BlogBandLeadershipBlogQuoteItem item={this.state.blogQuote} labels={this.props.labels} />
    );
}

标签: reactjs

解决方案


您似乎xxx()正确地调用了您的函数(尽管您不需要传递参数0- 这是不必要的)。问题可能在于,由于您在this内部使用xxx(),因此需要在构造函数中绑定函数。否则,this将不会引用您的组件,因此this.state.dataLoadedQuote将始终是虚假的。

所以添加:

this.xxx = this.xxx.bind(this);

您的构造函数现在可能看起来像:

constructor() {
  super();
  this.state = {}

  this.xxx = this.xxx.bind(this);
}

推荐阅读