我正在尝试制作标签组件.TabsSwitcher和TabsPanel必须是单独的组件,因此它们可以在DOM中的任何位置使用,例如TabsSwitcher不必跟随TabsPanel.
为了使它工作,我需要以某种方式连接这些组件.此外,TabsSwitcher必须能够在单击选项卡时告诉TabsPanel.
/** @jsx React.DOM */ var TabsExample = React.createClass({ render: function() { var tabs = [ {title: 'first', content: 'Content 1'}, {title: 'second', content: 'Content 2'} ]; return; } }); var TabsSwitcher = React.createClass({ render: function() { var items = this.props.items.map(function(item) { return {item.title}; }.bind(this)); return {items}; }, onClick: function(e) { // notify TabsContent about the click } }); var TabsContent = React.createClass({ render: function() { var items = this.props.items.map(function(item) { return{item.content}; }); return{items}; } }); React.renderComponent(, document.body );
最好的方法是什么?
解决方案:http://jsfiddle.net/NV/5YRG9/
React文档详细介绍了" 组件间通信 "和" 多个组件 ".要点是父级应该将一个函数作为prop传递给子级,并且子级应该在需要时将该函数作为回调函数调用:
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知道它们依赖于选项卡,并在状态更改时重新呈现:
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> ); } });