当用户点击特定主题时,我想传递道具的价值,这是" this.props.topicID"到其他组件。但是,当我尝试从其他组件访问时,它给出了未定义的错误。我们如何将props范围设置为global以便从其他组件进行访问。
var MainContainer = React.createClass({
render: function() {
return (
<div className="container">
<TopicsList />
</div>
);
}
});
var TopicsList = React.createClass({
getInitialState: function () {
return {
isTopicClicked : false,
topicPages
};
},
onClick: function (event) {
this.setState({isTopicClicked : true});
},
render: function () {
return (
<div>
<div className="row topic-list">
<SingleTopicBox
topicID="1"
onClick={this.onClick}
label="Topic"
/>
<SingleTopicBox
topicID="2"
onClick={this.onClick}
label="Topic"
/>
<SingleTopicBox
topicID="3"
onClick={this.onClick}
label="Topic"
/>
<SingleTopicBox
topicID="4"
onClick={this.onClick}
label="Topic"
/>
</div>
<div className="row">
{ this.state.isTopicClicked ? <SelectedTopicPage topicPages={topicPages} /> : null }
</div>
</div>
);
}
});
var SingleTopicBox = React.createClass({
render: function () {
return (
<div>
<div className="col-sm-2">
<div onClick={this.props.onClick.bind(null, this)} className="single-topic" data-topic-id={this.props.topicID}>
{this.props.label} {this.props.topicID}
</div>
</div>
</div>
);
}
});
var topicPages = [
{
topic_no: '1',
topic_page_no: '1',
headline: 'Topic 1 headline',
description: 'Topic 1 description comes here...',
first_topic_page: true,
last_topic_page: false
},
{
topic_no: '2',
topic_page_no: '2',
headline: 'Topic 2 headline',
description: 'Topic 2 description comes here...',
first_topic_page: false,
last_topic_page: false
},
{
topic_no: '3',
topic_page_no: '3',
headline: 'Topic 3 headline',
description: 'Topic 3 description comes here...',
first_topic_page: false,
last_topic_page: false
},
{
topic_no: '4',
topic_page_no: '4',
headline: 'Topic 4 headline',
description: 'Topic 4 description comes here...',
first_topic_page: false,
last_topic_page: true
}
];
var SelectedTopicPage = React.createClass({
render: function() {
return (
<div>
{this.props.topicPages.filter(function(topicPage) {
return topicPage.topic_no === '2'; // if condition is true, item is not filtered out
}).map(function (topicPage) {
return (
<SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
{topicPage.description}
</SelectedTopicPageMarkup>
);
})}
</div>
);
}
});
var SelectedTopicPageMarkup = React.createClass({
render: function() {
return (
<div className="topics-page">
<h1>{this.props.headline}</h1>
<p>{this.props.children}</p>
</div>
);
}
});
ReactDOM.render(<MainContainer />, document.getElementById('main-container'));
答案 0 :(得分:1)
看起来int
的{{1}}方法实际上应该是这样的:
onClick
然后,父TopicsList
组件可以将该信息作为道具传递给其他孩子。
然而,将整个组件推送到父组件有点麻烦。所以你可能想修改
onClick: function (childBoxWithClick) {
this.setState({
isTopicClicked : true,
lastClickedTopicId: childBoxWithClick.props.topicID
});
},
更具体的内容,如:
TopicsList
在这个例子中这应该可以正常工作,但是如果数据确实需要在整个应用程序中进行全局访问,则更复杂的情况可能需要使用Flux构造。