React和web components是为了解决不一样问题而创立的。web components为可重用组件提供了健壮的封装,而React提供了声明式的库来保持DOM和数据同步。这两点是互相补充的。做为一个开发者,你能够自由地在你的web components里使用React,或者在React里使用web components,或者二者同时使用。react
不少人使用React而不使用web components,可是你也许想要试一试,特别是若是你在使用依靠web components开发的第三方UI组件。git
在React里使用web componentsgithub
class HelloMessage extends React.Component { render() { return <div>Hello <x-search>{this.props.name}</x-search>!</div>; } }
注意:web
web components常常对实例暴露一个重要的接口,一个video web component也许会暴露play()和pause()函数。想要访问web component的接口,你将须要使用一个ref去与DOM节点直接交互。若是你使用第三方的web components,最好的解决方案就是写一个React组件来包裹web component。app
web components发出的事件也许不能正确地在React渲染树里传递。你将须要手动附加上事件处理器去处理这些事件在你的React组件里。ide
有一个混淆就是web component使用class而不是className。函数
function BrickFlipbox() { return ( <brick-flipbox class="demo"> <div>front</div> <div>back</div> </brick-flipbox> ); }
在web component里使用Reactthis
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});
你也能够看看这个连接完整的web component例子。google