W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
組件之間的交互還有另一種(不常見的)方法:對父組件要調(diào)用的子組件簡單的公開方法。
以一個待辦事項列表為例,點擊后該列表會被刪除。如果只剩下一個未完成的待辦事項,給它添加動畫:
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
實現(xiàn)了上述操作,并讓它在 componentDidUpdate
中檢查道具,然后對其本身進行動畫控制;然而,如果你傳遞不同的道具來控制動畫,這很快就會變得混亂。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: