var Tab = React.createClass({ getInitialState: function () { return {selected: false} }, handleSelected: function (status) { this.setState({selected: status}); }, render: function () { var cx = React.addons.classSet; var classes = cx({ 'react-tab': true, 'active': this.state.selected }); return ( <li className={classes}> <a href='#' data-index={this.props.index}>{this.props.children}</a> </li> ); } });
var TabList = React.createClass({ render: function () { return ( <ul className='react-tab-list'> {this.props.children} </ul> ); } });
var Tabs = React.createClass({ getInitialState: function () { return {selectedIndex: 0} }, componentDidMount: function () { var tabs = this.props.children[0].props.children, panels = this.props.children.slice(1), index = this.state.selectedIndex; for (i in tabs) { if (i == index) { tabs[i].handleSelected(true); panels[i].handleSelected(true); } else { tabs[i].handleSelected(false); panels[i].handleSelected(false); } } }, handleClick: function (e) { var index = parseInt(e.target.getAttribute('data-index')); var tabs = this.props.children[0].props.children, panels = this.props.children.slice(1); for (i in tabs) { if (i == index) { tabs[i].handleSelected(true); panels[i].handleSelected(true); } else { tabs[i].handleSelected(false); panels[i].handleSelected(false); } }
var Tabs = React.createClass({ render: function () { return ( <divclassName='react-tabs'> {this.props.children} </div> ); } });
因此我們需要一些動態指定 refs 的方法,而這個方法就是透過 cloneWithProps
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var App = React.createClass({ render: function () { var index = 0, children = React.Children.map(this.props.children, function (child) { return React.addons.cloneWithProps(child, { ref: 'child-' + (index++) }); });