10.Web Components(web组件)

2017-02-19  本文已影响0人  前端xiyoki

React版本:15.4.2
**翻译:xiyoki **

React和Web组件用于解决不同的问题。Web组件为可重用组件提供了强大的封装,而React提供了一个声明库,使DOM与你的数据保持同步。这两个目标是互补的。作为开发人员,你可以在你的Web组件中使用React,或者在React中使用Web组件,或者两者兼有。
大多数使用React的人不使用Web组件,但或许你希望使用,特别是你正在使用由Web组件编写而成的第三方UI组件。

Using Web Components in React(在React中使用Web组件)

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

注意:
Web组件经常暴露一些命令式API。例如,一个videoWeb组件可能会暴露play()pause() 函数。要访问Web组件的命令式API,你需要使用ref与DOM节点直接交互。如果你使用的是第三方Web组件,最好的解决方案是编写一个React组件,作为Web组件的包装器。

Web组件发出的事件可能无法通过React渲染树正确传播。你将需要手动添加事件处理程序来处理React组件中的这些事件。

一个常易混淆的地方是Web组件使用'class'而不是'className'。

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

Using React in your Web Components(在你的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});

查看完整示例 complete Web Components example on GitHub

上一篇 下一篇

猜你喜欢

热点阅读