mixins用法解析

雖然組件的原則就是模塊化,彼此之間相互獨(dú)立,但是有時(shí)候不同的組件之間可能會(huì)共用一些功能迂尝,共享一部分代碼鞠评。所以 React 提供了 mixins 這種方式來(lái)處理這種問(wèn)題茂蚓。

var SetIntervalMixin = {
    componentWillMount: function() {
        this.intervals = '';
    },
    setInterval: function(fn,time) {
        this.intervals = setInterval(fn,time)
        
    },
    componentWillUnmount: function() {
        clearTimeinterval(this.intervals)
    }
};

var TickTock = React.createClass({
    mixins: [SetIntervalMixin], // Use the mixin
    getInitialState: function() {
        return {seconds: 0,
              };
    },
    componentDidMount: function() {
        this.setInterval(this.tick.bind(this), 1000); // Call a method on the mixin
    },
    tick: function() {
        this.setState({seconds: this.state.seconds + 1});
    },
    render: function() {
        return (
            <p>
                React has been running for {this.state.seconds} seconds.
            </p>
        );
    }
});

上述是用es5語(yǔ)法寫(xiě)的mixin,每個(gè)組件都可以引入這個(gè)mixin在每個(gè)生命周期中調(diào)用剃幌。
Mixin 的特性一直廣泛存在于各種面向?qū)ο笳Z(yǔ)言聋涨。尤其在腳本語(yǔ)言中大都有原生支持,比如 Perl负乡、Ruby牍白、Python,甚至連 Sass 也支持抖棘。先來(lái)看一個(gè)在 Ruby 中使用 Mixin 的簡(jiǎn)單例子(裝個(gè)逼好嗎茂腥。。)

module D
  def initialize(name)
    @name = name
  end
  def to_s
    @name
  end
end

module Debug
  include D
  def who_am_i?
    "#{self.class.name} (\##{self.object_id}): #{self.to_s}"
  end
end

class Phonograph
  include Debug
  # ...
end

class EightTrack
  include Debug
  # ...
end

ph = Phonograph.new("West End Blues")
et = EightTrack.new("Real Pillow")
puts ph.who_am_i?  # Phonograph (#-72640448): West End Blues
puts et.who_am_i?  # EightTrack (#-72640468): Real Pillow

一層套一層切省,類型方法的公用最岗。
寫(xiě)過(guò)css的同學(xué)都知道,sass這種預(yù)編譯的語(yǔ)言也可以寫(xiě)出mixins朝捆。

// triangle
@mixin triangle($direction, $size, $borderColor ) 
{ content:""; height: 0; width: 0;
 @if $direction == top { 
 border-bottom:$size solid $borderColor;
 border-left:$size dashed transparent;
 border-right:$size dashed transparent; } 
@else if $direction == right {
 border-left:$size solid $borderColor;
 border-top:$size dashed transparent;
 border-bottom:$size dashed transparent; 
} @else if $direction == bottom { 
border-top:$size solid $borderColor; 
border-left:$size dashed transparent; 
border-right:$size dashed transparent; 
} @else if $direction == left { 
border-right:$size solid $borderColor; 
border-top:$size dashed transparent; 
border-bottom:$size dashed transparent; }
 }
定義了一個(gè)實(shí)現(xiàn)三角形的mixins般渡,參數(shù)依次為尖角朝向,大小,邊緣顏色诊杆。
如何使用呢
.div{@include triangle}

封裝一個(gè)mixins函數(shù)

const mixin = function(obj, mixins) {
  const newObj = obj;
  newObj.prototype = Object.create(obj.prototype); 

  for (let prop in mixins) {
    if (mixins.hasOwnProperty(prop)) {
      newObj.prototype[prop] = mixins[prop];
    }
  }

  return newObj;
}

const BigMixin = {
  fly: () => {
    console.log('I can fly');
  }
};

const Big = function() {
  console.log('new big');
};

Big.prototype.say = function(){
  console.log('hello')
}

const FlyBig = mixin(Big, BigMixin);

const flyBig = new FlyBig(); // 'new big'
flyBig.fly(); // 'I can fly'
flyBig.say() // 'hello'

如果對(duì)create這種寫(xiě)法不太了解的歼捐,可以點(diǎn)這里.

我么來(lái)再來(lái)寫(xiě)一個(gè)稍微復(fù)雜的mixin

var anotherMixin = {
      componentWillUpdate:function(newPro,newState){
            this.refs.input.value=''
            this.refs.input.focus()
            console.log(newState)
}

      change:function(e){
          if(e.keyCode == 13 && e.target.value != ''){
            ! localStorage.getITem('list') ? localStorage.setItem('list',[e.value]) :
            localStorage.getItem('list').indexOf(e.value) == -1 ? 
             this.setState({todos:this.state.todos.push(e.target.value),
             count:this.state.count++}) : ''
}

      setInterval: function(fn,time) {
        this.intervals = setInterval(fn,time)
        
    },
      componentWillUnmount: function() {
        clearTimeinterval(this.intervals)
    }
}

var TickTock = React.createClass({
    mixins: [SetIntervalMixin], // Use the mixin
    getInitialState: function() {
        return {todos: [],count:0,step:1
              };
    },
    componentDidMount: function() {
             this.setInterval(this.tick.bind(this), 1000); // Call a method on the mixin
   },
    tick: function() {
         if(thia.state.count >10){
             this.setState({todos:[],count:1.step:this.state.step++})
             
       }
    },
    render: function() {
        return (
           <p>當(dāng)前處于第{this.state.step}階段<p>
           <input ref = 'input' onkeydown = this.change.bind(this)>
          {this.state.todos.map (toto) => (
              <div>'-----' todo '------'
) }
        );
    }
});

我們做了這樣一件事情,有一個(gè)任務(wù)列表晨汹,我們可以往里面添加事情豹储,每次到了10之后,step上升一步淘这,同時(shí)會(huì)根據(jù)localstorage檢測(cè)是否有重復(fù)事件的添加剥扣。
最后我們來(lái)看一下如何在python中使用mixin吧

class SimpleItemContainer(object):
    def __init__(self, id, item_containers):
        self.id = id
        self.data = {}
        for item in item_containers:
            self.data[item.id] = item

class BetterSimpleItemContainer(object,SimpleItemContainer):
    def __getitem__(self, id):
        return self.data[id]

    def __setitem__(self, id, value):
      self.data[id] = value

    def __delitem__(self, id):
      del self.data[id]

    def keys(self):
            return self.data.keys()

其實(shí)就是一個(gè)類的繼承和復(fù)用而已,用到了一些特殊方法铝穷。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钠怯,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子曙聂,更是在濱河造成了極大的恐慌晦炊,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宁脊,死亡現(xiàn)場(chǎng)離奇詭異断国,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)榆苞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門稳衬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人坐漏,你說(shuō)我怎么就攤上這事薄疚。” “怎么了赊琳?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵街夭,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我慨畸,道長(zhǎng)莱坎,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任寸士,我火速辦了婚禮檐什,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘弱卡。我一直安慰自己乃正,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布婶博。 她就那樣靜靜地躺著瓮具,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上名党,一...
    開(kāi)封第一講書(shū)人閱讀 52,246評(píng)論 1 308
  • 那天叹阔,我揣著相機(jī)與錄音,去河邊找鬼传睹。 笑死耳幢,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的欧啤。 我是一名探鬼主播睛藻,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼邢隧!你這毒婦竟也來(lái)了店印?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤倒慧,失蹤者是張志新(化名)和其女友劉穎按摘,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體迫靖,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡院峡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年兴使,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了系宜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡发魄,死狀恐怖盹牧,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情励幼,我是刑警寧澤汰寓,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站苹粟,受9級(jí)特大地震影響有滑,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜嵌削,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一毛好、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧苛秕,春花似錦肌访、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春蟹演,著一層夾襖步出監(jiān)牢的瞬間风钻,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工酒请, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留魄咕,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓蚌父,卻偏偏與公主長(zhǎng)得像哮兰,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子苟弛,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容