加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React高级指南(十)【Web Components】

发布时间:2020-12-15 06:40:47 所属栏目:百科 来源:网络整理
导读:React和Web Component是为了解决不同的问题建立的。Web Component为可重用组件提供了强大的封装,然而React提供声明库,可以使得DOM和数据保持同步。两者的目标是互补的。作为开发者,你可以在你的Web Component中自由使用React,或者在React中使用Web Compo

React和Web Component是为了解决不同的问题建立的。Web Component为可重用组件提供了强大的封装,然而React提供声明库,可以使得DOM和数据保持同步。两者的目标是互补的。作为开发者,你可以在你的Web Component中自由使用React,或者在React中使用Web Component,或者都使用。

大多数使用React的开发者不使用Web Component,但是你可能想要使用Web Component,尤其是如果你正在使用Web Component编写的第三方的UI库的情况下。

在React中使用Web Components

class HelloMessage extends React.Component {
  render() {
    return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
  }
}

注意:

Web Components通常都会对外暴露一个必须的API,例如,对于一个video Web Component可能会暴露play()pause()为了访问Web Component的命令式API,您需要ref与DOM节点直接交互。如果你使用的是第三方的Web Component,最好的解决方案是编写React组件,作为Web Component的包装器。

由Web Component发出的事件可能不会沿着React渲染树正确传播。

因此在你的React组件中,你需要手动的添加事件处理程序来处理这些事件。

一个常见的困惑是Web Component使用class而不是className

function BrickFlipbox() {
  return (
    <brick-flipbox class="demo"> <div>front</div> <div>back</div> </brick-flipbox> ); }

在你的Web Component中使用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});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读