我有一个React.js应用程序,其构造如下:
// App component - represents the whole app
App = React.createClass({
render() {
return (
<div>
<Landing />
<Description />
<Skills/>
</div>
);
}
});
其中“Landing”,“Description”和“Skills”都是App组件的子组件。
在Landing中,我有一个名为Social Menu的子组件,使用:
进行调用<SocialMenu items={ ['Home', 'Services', 'About', 'Contact us']} />
看起来像这样:
SocialMenu = React.createClass({
getInitialState: function(){
return { focused: 0 };
},
componentDidMount: function() {
MichaelReactStore.addChangeListener(this.state.focused);
},
clicked: function(index){
// The click handler will update the state with
// the index of the focused menu entry
this.setState({focused: index});
},
render: function() {
// Here we will read the items property, which was passed
// as an attribute when the component was created
var self = this;
// The map method will loop over the array of menu entries,
// and will return a new array with <li> elements.
return (
<div>
<ul className="testblocks">{ this.props.items.map(function(m, index){
var style = '';
if(self.state.focused == index){
style = 'focused';
}
// Notice the use of the bind() method. It makes the
// index available to the clicked function:
return <li key={index} className={style} onClick={self.clicked.bind(self, index)}>{m}</li>;
}) }
</ul>
<p>Selected: {this.props.items[this.state.focused]}</p>
<ItemDetails item={ this.props.items[this.state.focused] } />
</div>
);
}
});
ItemDetails = React.createClass({
render: function() {
return (
<div>{this.props.item}</div>
);
}
});
我想做的是从社交菜单中将“状态向上发送”到App组件。然后我想将这些数据作为道具发送到技能组件,在那里它将根据该状态显示一些动态数据。
我该怎么做?谢谢!
(我知道这对于更大的应用程序来说是不可持续的,但对于这个应用程序,我只需要一个简单的解决方案)
答案 0 :(得分:1)
我将管理根组件中的状态,并在您需要的所有组件中使focused
成为属性(this.props.focused
)。您现在在setState
执行回调的地方,如下所示:
this.props.onFocusChanged(index)
您将此回调作为属性提供给着陆,并在Landing
中将其作为属性提供给SocialMenu
。您的应用程序看起来像这样:
App = React.createClass({
getInitialState: function(){
return { focused: 0 };
},
clicked: (index) => {
this.setState({focused: index});
},
render() {
return (
<div>
<Landing onFocusChanged={this.clicked} focused={this.state.focused} />
<Description />
<Skills focused={this.state.focused}/>
</div>
);
}
});