如何在 react 中的方法之间进行通信

How to communicate between methods in react?

本文关键字:之间 通信 方法 react      更新时间:2023-09-26

我目前SelectedTopicPage组件中有两个方法,分别是navigateNextrender。我想将topicPageNo的值从navigateNext方法传递到render方法。在 React 中推荐的方法是什么?当我尝试声明时:

topicPageNo = navigateNext.state.topicPageNo;

它给了undefined error.

var SelectedTopicPage = React.createClass({
    navigateNext: function() {
        let topicPageNo = '2';
        this.setState({topicPageNo : topicPageNo});
    },
    render: function() {
        let topicsID = this.props.topicsID;
        let navigateNext = this.navigateNext;
        let topicPageNo = navigateNext.state.topicPageNo;
        return (
            <div>
                {this.props.topicPages.filter(function(topicPage) {
                    return topicPage.topic_no === topicsID && topicPage.topic_page_no === topicPageNo; // if condition is true, item is not filtered out
                }).map(function (topicPage) {
                    return (
                        <div>
                            <div>
                            <SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
                                {topicPage.description}
                            </SelectedTopicPageMarkup> 
                            </div>
                            <div>
                                <NextPrevBtn moveNext={navigateNext}/>
                            </div>
                        </div>
                    );
                })}
            </div>
        );
    }
});

你必须使用this,所以你的代码应该let topicPageNo = this.state.topicPageNo;

并且您的组件应该具有类似

getInitialState:function()
    {
      return{
        topicPageNo:0
      }
    }