React mixins详解

**

**`// Mixins有点类似AOP。所谓的mixins就是将组件里的方法抽出来。实际上Mixins里的this是指向组件的,使用了Mixins以后,组件也可以调用Mixins里的方法。
//
Mixins里也可以编写组件生命周期的方法,需要注意的是:Mixins里的方法并不会覆盖组件的生命周期方法,会在先于组件生命周期方法执行。
// 组件也可以使用多个Mixin 数组引入的顺序,决定了Mxins里生命周期方法的执行顺序。 // 不允许重复 //
除了生命周期方法可以重复以外,其他的方法都不可以重复,否则会报错**

**

    const stateMixins = {
        componentWillMount() { // 在这里设值不会造成二次渲染
            console.log('componentWillMount')
            this.oldStatus = []
        },
        componentWillUpdate(nextProp, nextState) { // 这里做数据处理
            console.log('componentWillUpdate')
            this.oldStatus.push(nextState)
        },
        getPreStatus() {
            let index = this.oldStatus.length - 1
            return index == -1 ? 'null' : this.oldStatus[index]
        },
    };
    const TextMixins = React.createClass({
        mixins: [stateMixins],
        getInitialState:function() {
            console.log('getInitialState')
            return {
                count: 0
            }
        },
        getDefaultProps() {
            console.log('getDefaultProps')
        },
        componentDidMount(){ // 在这里可以获取DOM节点  ajax请求获取数据 操作dom
            console.log('componentDidMount')
        },
        componentDidUpdate() { // 可以获取组件dom
            console.log('componentDidUpdate')
        },
        addCount() {
            this.setState({
                count: this.state.count + 1
            })
            console.log('count=='+this.getPreStatus().count)
        },
        render:function(){
            console.log('render')
            return(
                <div>
                    <p>我是组件一textMixins</p>
                    <p>count:{this.state.count}</p>
                    <button onClick={this.addCount}>测试</button>
                    <SubSubCom/>
                </div>
            )
        }
    });
    const SubSubCom = React.createClass({
        render() {
            return (
                <div>
                    <p>我是组件二SubSubCom</p>
                </div>
            )
        }
    })
    React.render(<TextMixins/>, document.getElementById('app'));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值