React高级指南(十)【Web Components】
React和Web Component是为了解决不同的问题建立的。Web Component为可重用组件提供了强大的封装,然而React提供声明库,可以使得DOM和数据保持同步。两者的目标是互补的。作为开发者,你可以在你的Web Component中自由使用React,或者在React中使用Web Component,或者都使用。 大多数使用React的开发者不使用Web Component,但是你可能想要使用Web Component,尤其是如果你正在使用Web Component编写的第三方的UI库的情况下。 在React中使用Web Componentsclass HelloMessage extends React.Component {
render() {
return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
}
}
一个常见的困惑是Web Component使用 function BrickFlipbox() {
return (
<brick-flipbox class="demo"> <div>front</div> <div>back</div> </brick-flipbox> ); }
在你的Web Component中使用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});
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |