我正在尝试制作选项卡组件。TabsSwitcher和TabsPanel必须是单独的组件,因此它们可以在DOM中的任何位置使用,例如TabsPanel不必跟随TabsSwitcher。
为了使其正常工作,我需要以某种方式连接这些组件。此外,TabsSwitcher必须能够告诉TabsPanel单击选项卡的时间。
/** @jsx React.DOM */ var TabsExample = React.createClass({ render: function() { var tabs = [ {title: 'first', content: 'Content 1'}, {title: 'second', content: 'Content 2'} ]; return <div> <TabsSwitcher items={tabs}/> <TabsContent items={tabs}/> </div>; } }); var TabsSwitcher = React.createClass({ render: function() { var items = this.props.items.map(function(item) { return <a onClick={this.onClick}>{item.title}</a>; }.bind(this)); return <div>{items}</div>; }, onClick: function(e) { // notify TabsContent about the click } }); var TabsContent = React.createClass({ render: function() { var items = this.props.items.map(function(item) { return <div>{item.content}</div>; }); return <div>{items}</div>; } }); React.renderComponent( <TabsExample/>, document.body );
最好的方法是什么?
解决方案:http : //jsfiddle.net/NV/5YRG9/
React文档在“ 组件之间通信 ”和“ 多个组件 ”中对此进行了详细介绍。要点是,父级应将一个函数作为道具传递给子级,而子级在需要以下情况时应将该函数作为回调调用:
var TabsExample = React.createClass({ handleTabClick: function(item) { // Do something with item, maybe set it as active. }, render: function() { var tabs = [ {title: 'first', content: 'Content 1'}, {title: 'second', content: 'Content 2'} ]; return <div> <TabsSwitcher items={tabs} onTabClick={this.handleTabClick}/> <TabsContent items={tabs}/> </div>; } }); var TabsSwitcher = React.createClass({ render: function() { var items = this.props.items.map(function(item) { return <a onClick={this.onClick.bind(this, item)}>{item.title}</a>; }.bind(this)); return <div>{items}</div>; }, onClick: function(item) { this.props.onTabClick(item); } });
对于TabsContent组件,您应该将其tabs移入TabsExample状态,以便React在更改时可以自动为您重新渲染。由于TabsSwitcher和TabsContent是通过render方法中的选项卡传递的,因此React知道它们依赖于选项卡,并且在状态更改时会重新渲染:
TabsContent
tabs
TabsExample
TabsSwitcher
var TabsExample = React.createClass({ getInitialState: function() { return { activeTabId: 1, tabs: [ {title: 'first', content: 'Content 1', id: 1}, {title: 'second', content: 'Content 2', id: 2} ] }; }; handleTabClick: function(item) { // Call `setState` so React knows about the updated tab item. this.setState({activeTabId: item.id}); }, render: function() { return ( <div> <TabsSwitcher items={this.state.tabs} activeItemId={this.state.activeTabId} onTabClick={this.handleTabClick}/> <TabsContent items={this.state.tabs} activeItemId={this.state.activeTabId}/> </div> ); } });