公開組件功能

2019-08-14 14:31 更新

組件之間的交互還有另一種(不常見的)方法:對父組件要調(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中檢查道具,然后對其本身進行動畫控制;然而,如果你傳遞不同的道具來控制動畫,這很快就會變得混亂。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號