組件之間的交互還有另一種(不常見的)方法:對父組件要調(diào)用的子組件簡單的公開方法。
以一個(gè)待辦事項(xiàng)列表為例,點(diǎn)擊后該列表會(huì)被刪除。如果只剩下一個(gè)未完成的待辦事項(xiàng),給它添加動(dòng)畫:
var Todo = React.createClass({ render: function() { return <div onClick={this.props.onClick}>{this.props.title}</div>; }, //this component will be accessed by the parent through the `ref` attribute animate: function() { console.log('Pretend %s is animating', this.props.title); } });var Todos = React.createClass({ getInitialState: function() { return {items: ['Apple', 'Banana', 'Cranberry']}; }, handleClick: function(index) { var items = this.state.items.filter(function(item, i) { return index !== i; }); this.setState({items: items}, function() { if (items.length === 1) { this.refs.item0.animate(); } }.bind(this)); }, render: function() { return ( <div> {this.state.items.map(function(item, i) { var boundClick = this.handleClick.bind(this, i); return ( <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} /> ); }, this)} </div> ); } }); React.render(<Todos />, mountNode);
或者,你可能已經(jīng)通過把 isLastUnfinishedItem
道具傳遞給 todo
實(shí)現(xiàn)了上述操作,并讓它在 componentDidUpdate
中檢查道具,然后對其本身進(jìn)行動(dòng)畫控制;然而,如果你傳遞不同的道具來控制動(dòng)畫,這很快就會(huì)變得混亂。
更多建議: