custom组件新增renderChild,用于自定义扩展容器区域 (#4015)

* docs: 剔除多余注释

* fix: 右键菜单支持多主题配置

* style: 将tabs的toolbar改成默认右侧展示

* style: 修正select的placeholder的color色值

* feat: custom组件新增renderChild,用于自定义扩展容器区域

* doc: 增加了点注释

* fix: 修正一个错别字

* docs: 代码prettier一下

* fix(custom 组件): 完善renderChild,以便用户可以直接使用amis中的dom参数对象

* fix(custom组件): 补充销毁子节点的逻辑

* fix(custom): 调整下参数命名
This commit is contained in:
刘丹 2022-04-13 14:50:43 +08:00 committed by GitHub
parent 7340576d67
commit 260cbc1436
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 1 deletions

View File

@ -1,5 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import memoize from 'lodash/memoize';
import isString from 'lodash/isString';
import {Renderer, RendererProps} from '../factory';
import {anyChanged} from '../utils/helper';
@ -50,6 +52,8 @@ export class Custom extends React.Component<CustomProps, object> {
onMount: Function = () => {};
onUnmount: Function = () => {};
childElemArr: HTMLElement[] = []; // 用于记录子元素的Dom节点以便销毁
constructor(props: CustomProps) {
super(props);
this.dom = React.createRef();
@ -86,6 +90,9 @@ export class Custom extends React.Component<CustomProps, object> {
this.onUnmount = props.onUnmount;
}
}
this.renderChild = this.renderChild.bind(this);
this.recordChildElem = this.recordChildElem.bind(this);
this.unmountChildElem = this.unmountChildElem.bind(this);
}
componentDidUpdate(prevProps: CustomProps) {
@ -102,6 +109,51 @@ export class Custom extends React.Component<CustomProps, object> {
componentWillUnmount() {
this.onUnmount(this.props);
// 自动销毁所有子节点
this.unmountChildElem();
}
// 记录子元素的dom节点
recordChildElem(insertElem: HTMLElement) {
if (insertElem && !this.childElemArr.some(item => item === insertElem)) {
this.childElemArr.push(insertElem);
}
}
// 销毁所有子元素的dom节点
unmountChildElem() {
if (this.childElemArr && this.childElemArr.length > 0) {
this.childElemArr.forEach(childElemItem => ReactDOM.unmountComponentAtNode(childElemItem));
}
}
/**
*
* custom组件通过props.render生成的子元素是react虚拟dom对象使ReactDOM.render渲染dom中
**/
renderChild(schemaPosition: string, childSchema: any, insertElemDom: HTMLElement | string) {
const {render} = this.props;
let childEleCont = null;
let curInsertElemDom: any = null;
if (isString(insertElemDom)) {
const _curInsertElem = document.getElementById(insertElemDom);
if (_curInsertElem) {
curInsertElemDom = _curInsertElem as HTMLElement;
}
} else {
curInsertElemDom = insertElemDom;
}
if (childSchema && curInsertElemDom) {
const childHTMLElem = render(schemaPosition, childSchema);
childEleCont = ReactDOM.render(
childHTMLElem,
curInsertElemDom,
() => {
this.recordChildElem(curInsertElemDom);
}
);
}
return childEleCont;
}
render() {

View File

@ -27,7 +27,7 @@ export interface WebComponentSchema extends BaseSchema {
/**
*
*/
prpos?: {
props?: {
[propName: string]: any;
};
}