?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
React和Web組件的構(gòu)建是為了解決不同的問題。Web組件為可重用組件提供了強大的封裝,而React提供了一個聲明庫來保持DOM與數(shù)據(jù)同步。這兩個目標是相輔相成的。作為開發(fā)人員,您可以在Web組件中自由使用React,或者在React中使用Web組件,或者同時使用這兩種組件。
大多數(shù)使用React的人不使用Web組件,但可能需要使用Web組件,尤其是在使用使用Web組件編寫的第三方UI組件時。
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()
起作用。要訪問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> ); }
class XSearch extends HTMLElement { connectedCallback() { const mountPoint = document.createElement('span'); this.attachShadow({ mode: 'open' }).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); } } customElements.define('x-search', XSearch);
注意:如果您使用Babel轉(zhuǎn)換類,此代碼將不起作用。請參閱此問題以進行討論。