React版本:15.4.2
**翻譯:xiyoki **
React和Web組件用于解決不同的問題蟆淀。Web組件為可重用組件提供了強大的封裝,而React提供了一個聲明庫澡匪,使DOM與你的數(shù)據(jù)保持同步熔任。這兩個目標(biāo)是互補的。作為開發(fā)人員唁情,你可以在你的Web組件中使用React疑苔,或者在React中使用Web組件,或者兩者兼有甸鸟。
大多數(shù)使用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組件經(jīng)常暴露一些命令式API趁餐。例如,一個video
Web組件可能會暴露play()
和pause()
函數(shù)篮绰。要訪問Web組件的命令式API后雷,你需要使用ref與DOM節(jié)點直接交互。如果你使用的是第三方Web組件吠各,最好的解決方案是編寫一個React組件臀突,作為Web組件的包裝器。
Web組件發(fā)出的事件可能無法通過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});