10.Web Components(web組件)

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。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容