React学习(11)—— 高阶应用:Web组件
Web组件从概念上说,React 和 Web组件分别用于解决不同的问题。Web组件提供了强大的封装特性来支持其可重复使用性,而React提供了一系列声明性(declarative)接口保证Dom结构和数据同步。但是某些时候这2个目标是互补的。对于开发人员来说将React用于Web组件、或将Web组件用于React、或2者皆有并非难事。 虽然大部分使用React的开发人员并不需要使用Web组件,但是在某些情况,特别是引入了某些第三方库,还是需要使用到相关机制。 在React中使用Web组件class HelloMessage extends React.Component { render() { return <div>Hello <x-search>{this.props.name}</x-search>!</div>; } }
一个经常导致混乱的地方是,Web组件使用的是“class”而React使用的是“className”,例如: function BrickFlipbox() { return ( <brick-flipbox class="demo"> <div>front</div> <div>back</div> </brick-flipbox> ); } 在Web组件中使用Reactconst 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}); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |