学习React系列(七)——Fragments、Portals、Error Boundaries与WEB组件
Error Boundaries
React.Fragment
想象一个场景,想把td包装为组件添加到table中去,代码如下:
class MyTable extends React.PureComponent {
render() {
rejturn(
<table>
<tbody
<tr>
<MyTd></MyTd>
</tr>
</table>
</tbody>
)
}
}
class MyTd extends React.PureComponent {
render() {
return(
<React.Fragment>
<td>a</td><td>a</td>
</React.Fragment>
)
}
}
自定义的MyTable中插入自定义的MyTd.....,对不起直接报错,tr的子元素只能为td而实际上中间还套了一层div。。。。。
为了解决如上问题React.Fragment横空出世
class MyTd extends React.PureComponent {
render() {
return(
<React.Fragment key={1}>
<td>a</td><td>a</td>
</React.Fragment>
)
}
}
补充一下,React.Fragment暂时只支持key这一个属性,还有它可以写成<></>这样的形式,当然它也可以用来减少dom结构的嵌套,如果你不想用二外的div来包裹内容,那么可以使用改组件,其和原生的DocumentFragment相似。
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
portals
想象两个个场景:一、点击父组件中的一个按钮,弹出个弹框,弹框面积要求大于父组件。
场景一解决方案就是将弹窗挂到其他的Dom上面
class Mask extends React.PureComponent {
render() {
return (
//这里我很想知道为什么如果不加top,那么弹窗默认加到最初的div下面
<div style={{position: "absolute",top:"0", width: '400px', height: '400px', border: '1px solid red',pointerEvents:"none" }}></div>
)
}
} class Parent extends React.PureComponent {
constructor(props) {
super(props)
this.state = {
show: false
}
this.show = this.show.bind(this)
}
show() {
let show = !this.state.show
this.setState({
show
})
} render() {
return (
<div style={{ width: '100px', height: '100px', border: '1px solid black' }}>
<button onClick={this.show}>展示弹窗</button>
{this.state.show && ReactDOM.createPortal(<Mask />, document.getElementById('root'))}
</div>
) }
}
结论:对于 portal 的一个典型用例是当父组件有 overflow: hidden
或 z-index
样式,但你需要子组件能够在视觉上“跳出(break out)”其容器。例如,对话框、hovercards以及提示框。
二、组件a与b同级,要求组件b可以捕获a中的某个事件
//index.html中的代码 <html>
<body>
<div id="app-root"></div>
<div id="modal-root"></div>
</body>
</html> //reactjs
const appRoot = document.getElementById('app-root');
const modalRoot = document.getElementById('modal-root'); class Modal extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
} componentDidMount() {
modalRoot.appendChild(this.el);
} componentWillUnmount() {
modalRoot.removeChild(this.el);
} render() {
return ReactDOM.createPortal(
// this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。
this.props.children,
this.el,
);
}
} class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {clicks: 0};
this.handleClick = this.handleClick.bind(this);
} handleClick() {
// This will fire when the button in Child is clicked,
// updating Parent's state, even though button
// is not direct descendant in the DOM.
this.setState(prevState => ({
clicks: prevState.clicks + 1
}));
} render() {
return (
<div onClick={this.handleClick}>
<p>Number of clicks: {this.state.clicks}</p>
<p>
Open up the browser DevTools
to observe that the button
is not a child of the div
with the onClick handler.
</p>
<Modal>
<Child />
</Modal>
</div>
);
}
} function Child() {
// The click event on this button will bubble up to parent,
// because there is no 'onClick' attribute defined
return (
<div className="modal">
<button>Click</button>
</div>
);
} ReactDOM.render(<Parent />, appRoot);
尽管 portal 可以被放置在 DOM 树的任何地方,但在其他方面其行为和普通的 React 子节点行为一致。包含事件冒泡。一个从 portal 内部会触发的事件会一直冒泡至包含 React 树 的祖先。由于 portal 存在于 React 树中,而不用考虑其在 DOM 树中的位置。
Error Boundaries
解决的问题:部分 UI 的异常不应该破坏了整个应用
不适用的场景:
- 事件处理 (了解更多)(使用try/catch)
- 异步代码 (例如
setTimeout
或requestAnimationFrame
回调函数) - 服务端渲染
- 错误边界自身抛出来的错误 (而不是其子组件)
为什么不用try/catch
try/catch 用于命令式而react组件是声明式的(jsx无法识别)声明什么需要被渲染
在react16+版本中如果使用错误边界,若错误边界中的组件出现错误,只要能被捕获,那么应用不会整体崩溃,否则,应用将整体unmount。
用开发模式的时候错误边界中组件出错会有警告提示如下:
点击右上角的X之后回到页面仍会看到组件,代表组件并没有崩溃
遗留问题:不知道在生成模式中还会不会弹出这个错误提示,个人觉得不应该存在,否则太影响体验了,我也不知道如何运行生产模式的react,希望知道的可以留言
WEB组件
定义:通过一种标准化的非侵入的方式封装一个组件,每个组件能组织好它自身的 HTML 结构、CSS 样式、JavaScript 代码,并且不会干扰页面上的其他代码
下面来看一个例子,该页面名字为favorite-color.html:
<!-- WebComponent example based off element-boilerplate: https://github.com/webcomponents/element-boilerplate -->
<template>
<style>
.coloured {
color: red;
}
</style>
<p>My favorite colour is: <strong class="coloured">Red</strong></p>
</template>
<script>
(function() {
// Creates an object based in the HTML Element prototype
var element = Object.create(HTMLElement.prototype);
// Gets content from <template>
var template = document.currentScript.ownerDocument.querySelector('template').content;
// Fires when an instance of the element is created
element.createdCallback = function() {
// Creates the shadow root
var shadowRoot = this.createShadowRoot();
// Adds a template clone into shadow root
var clone = document.importNode(template, true);
shadowRoot.appendChild(clone);
};
document.registerElement('favorite-colour', {
prototype: element
});
}());
</script>
在另一个html页面中引入上面的组件:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>My First WebComponent</title>
<link rel="import" href="components/favorite-colour.html" />
</head>
<body>
<favorite-colour></favorite-colour>
</body>
</html>
目前已经有三个基于 WebComponent 标准的框架:X-Tag, Polymer, Bosonic
注意:若你正在使用第三方Web组件,其最好的解决方案是编写一个 React组件,以包装该 Web组件。由Web组件触发的事件可能无法通过React渲染树来正确冒泡。
你需要手动捕获事件处理器以处理那些在React组件里的事件。
参考:https://reactjs.org/docs/fragments.html
https://doc.react-china.org/docs/error-boundaries.html
http://blog.csdn.net/meikidd/article/details/44628915
最新文章
- 第3章 Linux常用命令(1)_文件处理命令
- TP数据访问
- sentinel搭建redis集群经验总结
- PHP设计模式之装饰者模式
- NSMutableString
- [POJ3352]Road Construction(缩点,割边,桥,环)
- OpenCV学习目录(持续更新)
- MySQL Workbench 6.3 CE 不显示MySql、infomation_schema等数据库
- samba服务器概述
- PHP学习笔记二十七【重写】
- perl lwp关闭ssl校验
- spring 事务 笔记3.1
- 团队作业4——第一次项目冲刺 FiFtH DaY
- cookie和session的那些事
- Cherrypy文件上传非ASCII文件名乱码问题解决
- Django 配置文件settings注解(含静态文件和上传文件配置)
- OI生涯回忆录 2018.11.12~2019.4.15
- 结构体变量的 extern 使用方法,转--
- Druid 在有赞的实践
- html5-列表