2017-09-23 39 views
0

React文檔提供瞭如何在webcomponent內使用反應的示例。但提供的the example是微不足道的,並不足以吸取教訓。特別是它沒有提供關於如何從webcomponent冒出一個事件的信息。將React事件轉換爲Webcomponent事件

假設代碼開始作爲

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(<input onchange={....} value={...}></input>, mountPoint); 
    } 
    } 
}); 
document.registerElement('x-search', {prototype: proto}); 

這將如何進行佈線?

回答

0

那怎麼樣而不是使用xeact

定義組件:

import xeact, {exposed, dispatchEvent, Component} from 'xeact'; 

@xeact('search') 
export default class Search extends Component { 

    state = { 
     value: '', 
    }; 

    onChange(e) { 
     const value = e.target.value; 
     this.setState({ 
      value 
     },() => { 
      dispatchEvent(this, 'change' , { 
       value 
      }); 
     }); 
    } 

    @exposed 
    get value() { 
     return this.state.value; 
    } 

    render() { 
     const {value} = this.state; 
     return <span> 
      <input value={value} onChange={(e) => {this.onChange(e)}} /> 
     </span> 
    } 
} 

從HTML使用它:

<x-search></x-search> 
<script> 
    // get value from `change` event 
    document.querySelector('x-search').addEventListener('change', function(e) { 
     console.log(e.detail.value); 
    }); 

    // get value from getter 
    document.querySelector('x-search').value; 
</script>