如何通过变量外部方法的范围进行反应?

时间:2016-01-22 13:38:07

标签: javascript reactjs

我在abc方法中有一个变量render,并希望将变量传递给navigateNext方法。我知道我们可以在外面声明一个全局变量。但是,我想知道是否有反应的方法。

var SelectedTopicPage = React.createClass({
    getInitialState: function() {
      return{
        topicPageNo: 0,
        total_selected_topic_pages: 1
      }
    },
    navigateBack: function() {
        let topicPageNo;
        if (this.state.topicPageNo > 0){
            topicPageNo = this.state.topicPageNo - 1;   
        }
        else {
            topicPageNo = 0;
        }
        this.setState({topicPageNo : topicPageNo});
    },
    navigateNext: function() {
        let topicPageNo = this.state.topicPageNo + 1;
        this.setState({topicPageNo : topicPageNo});
        console.log(abc);
    },
    render: function() {
        let topicsID = this.props.topicsID;
        let navigateNext = this.navigateNext;
        let navigateBack = this.navigateBack;
        let topicPageNo = this.state.topicPageNo;
        return (
            <div>
                {this.props.topicPages.filter(function(topicPage) {
                    return topicPage.topic_no === topicsID; // if condition is true, item is not filtered out
                }).map(function (topicPage) {
                    let abc = topicPage.topic_pages.length;
                    return (
                        <div>
                            <div>
                            <SelectedTopicPageMarkup headline={topicPage.topic_pages[0].headline} key={topicPage.topic_no}>
                                {topicPage.topic_pages[topicPageNo].description}
                            </SelectedTopicPageMarkup> 
                            </div>
                            <div>
                                <NextPrevBtn moveNext={navigateNext} moveBack={navigateBack}/>
                            </div>
                        </div>
                    );
                })}
            </div>
        );
    }
});

1 个答案:

答案 0 :(得分:1)

abc作为navigateNext函数的输入参数。 (旁白:请给它一个比abc更好的名字。)

navigateNext: function (abc) {
    let topicPageNo = this.state.topicPageNo + 1;
    this.setState({topicPageNo : topicPageNo});
    console.log(abc);
},

现在在定义函数回调的地方使用它:

<NextPrevBtn moveNext={this.navigateNext.bind(this, abc)} moveBack={this.navigateBack}/>

您还需要对传递给bind的匿名函数使用map,以确保this在范围内。即。

}).map(function (topicPage) {
    let abc = topicPage.topic_pages.length;
    return (
        /* etc */
    );
}.bind(this))}