我在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>
);
}
});
答案 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))}