Web组件
从概念上说,React 和 Web组件分别用于解决不同的问题。Web组件提供了强大的封装特性来支持其可重复使用性,而React提供了一系列声明性(declarative)接口保证Dom结构和数据同步。但是某些时候这2个目标是互补的。对于开发人员来说将React用于Web组件、或将Web组件用于React、或2者皆有并非难事。@H_404_5@
虽然大部分使用React的开发人员并不需要使用Web组件,但是在某些情况,特别是引入了某些第三方库,还是需要使用到相关机制。@H_404_5@
在React中使用Web组件
- class HelloMessage extends React.Component {
- render() {
- return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
- }
- }
Web组件常会暴露一些必要的API接口,例如一个 video Web组件可能会暴露
play()
和pause()
方法。为了获取Web组件暴露的这些API接口,需要在React编码使用Refs特性来直接获取真实的Dom节点。如果引入第三方的Web组件,最好的解决方案使用一个React组件来包装引入的Web组件并最终作为一个React组件来使用。@H_404_5@由第三方Web组件触发的事件也许并不能通过React的渲染树传递,此时需要在组件中去手工的触发事件。@H_404_5@
一个经常导致混乱的地方是,Web组件使用的是“class”而React使用的是“className”,例如:@H_404_5@
在Web组件中使用React
- const proto = Object.create(HTMLElement.prototype,{
- attachedCallback: {
- value: function() {
- const mountPoint = document.createElement('span');
- this.createShadowRoot().appendChild(mountPoint);
- const name = this.getAttribute('name');
- const url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
- ReactDOM.render(<a href={url}>{name}</a>,mountPoint);
- }
- }
- });
- document.registerElement('x-search',{prototype: proto});