React学习笔记

React进阶笔记13(Web Components)

2018-08-22  本文已影响0人  XKolento

React 和 web组件 被用以解决不同问题。web组件为可重用的组件提供了强大的封装能力。React则是保持DOM和数据同步的声明式库,二者的目标互补。作为开发者,可以随意的在React中使用web组件,也可以在web组件中使用React。

大部分使用React的开发者并不使用 web组件,但你可能想要,尤其若你正在使用那些用 Web组件编写的第三方UI组件。

在React中使用web组件

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

注意
web组件通常暴露一个必要的API,例如一个 video 组件就有可能会暴露 play() 和 pause() 方法。
为了访问组件必要的API,你需要使用一个引用,能够直接和dom节点交互。
如果正在使用第三方web组件,最好的方法是编写一个React组件,来包装这个第三方组件。

由web组件触发的事件,可能无法通过React的事件树渲染来正确的冒泡。
只能通过手动处理器来处理那些React组件里面的事件。

一个普遍的问题就是:
web组件中使用 class 而不是 className

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

在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});
上一篇 下一篇

猜你喜欢

热点阅读