将React事件转换为Web组件事件

时间:2017-09-23 06:15:06

标签: reactjs web-component

React文档提供了如何在web组件内使用react的示例。但是the example提供的是微不足道的,而且还不足以学习。特别是它不提供有关如何从Web组件中冒出事件的信息。

假设代码以

开头
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});

如何连线?

1 个答案:

答案 0 :(得分: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>