zsmj
3 years ago
2 changed files with 89 additions and 8 deletions
@ -0,0 +1,80 @@
|
||||
# 在props中处理生命周期函数 |
||||
|
||||
在[组件生命周期](http://fanruan.design/doc.html?post=244ba71889)一文中,详细解释了组件中各个生命周期钩子的执行时机.那么是不是我们想要使用生命周期钩子,就一定要写一个组件类呢?答案是否定的. |
||||
|
||||
类似于[9、高阶组件的render-props](https://code.fanruan.com/dailer/FineUI-100-Questions/src/branch/master/questions/4.高阶组件的render-props.md)文中所讲,render可以通过props指定,那么beforeRender,mounted等其他生命周期函数可否通过props控制呢? 如果和类组件中方法产生冲突,又是如何处理的呢? |
||||
|
||||
FineUI中有两种处理方式直接覆盖和一并执行 |
||||
|
||||
直接覆盖的有: beforeInit,beforeRender,render. 如果在props中指定了相应生命周期钩子,则组件类内的方法不会执行 |
||||
|
||||
一并执行的有: beforeCreate,created,beforeMount,mounted,beforeDestroy,destroyed,beforeUpdate,updated,如果在props中指定了相应生命周期钩子,则按照先执行类方法,再执行props中方法的顺序依次执行 |
||||
|
||||
如下示例,最终的输出会是什么呢? |
||||
|
||||
```demo |
||||
const logs = []; |
||||
|
||||
const Menus = BI.inherit(BI.Widget, { |
||||
|
||||
beforeRender: function () { |
||||
logs.push("内部的beforeRender"); |
||||
return Promise.resolve(); |
||||
}, |
||||
|
||||
render: function () { |
||||
logs.push("内部的render"); |
||||
return { |
||||
type: "bi.button", |
||||
text: "内部的render", |
||||
}; |
||||
}, |
||||
|
||||
beforeMount: function () { |
||||
logs.push("内部的beforeMount"); |
||||
}, |
||||
|
||||
mounted: function () { |
||||
logs.push("内部的beforeMount"); |
||||
}, |
||||
|
||||
setText: function (text) { |
||||
this.button.setText(text); |
||||
}, |
||||
}); |
||||
|
||||
BI.shortcut("demo.menus", Menus); |
||||
|
||||
const Widget10 = BI.createWidget({ |
||||
type: "bi.vertical", |
||||
items: [ |
||||
{ |
||||
el: { |
||||
type: "demo.menus", |
||||
beforeRender: () => { |
||||
logs.push("外面的beforeRender"); |
||||
return Promise.resolve(); |
||||
}, |
||||
render: function () { |
||||
logs.push("外面的render"); |
||||
return { |
||||
type: "bi.label", |
||||
ref: (_ref) => { |
||||
this.button = _ref; |
||||
}, |
||||
text: "外面的render", |
||||
whiteSpace: "normal", |
||||
}; |
||||
}, |
||||
beforeMount: () => { |
||||
logs.push("外面的beforeMount"); |
||||
}, |
||||
mounted: function () { |
||||
logs.push("外面的mounted"); |
||||
this.setText(logs.join("\n")); |
||||
}, |
||||
}, |
||||
}, |
||||
], |
||||
}); |
||||
``` |
Loading…
Reference in new issue