@samitouri / QOS-React / commits / b7a2409919

ref-09-webcomponents.zh-CN.md (#6561)

Minwei Xu committed Apr 20, 2016 at 20:07 UTC b7a2409919215179d7d291c62b0ef8499616f91c
1 file changed +56
docs/docs/ref-09-webcomponents.zh-CN.md new
+56
@@ -0,0 +1,56 @@
1 +---
2 +id: webcomponents-zh-CN
3 +title: Web Components
4 +permalink: webcomponents-zh-CN.html
5 +prev: reconciliation-zh-CN.html
6 +next: glossary-zh-CN.html
7 +---
8 +
9 +因为React和Web组件是用来解决不同问题的, 试图比较两者将不可避免地导致似是而非的结论, 。Web组件为可复用组件提供了强大的封装, 而React则提供了一个使DOM与你的数据同步的声明式库。两者的目标是互补的;工程师可以混合使用这些技术。作为一个开发者,你可以在你的Web组件中使用React,或者在React中使用Web组件,或者两者一起使用。
10 +
11 +## 在React中使用Web组件
12 +
13 +```javascript
14 +class HelloMessage extends React.Component{
15 + render() {
16 + return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
17 + }
18 +}
19 +```
20 +
21 +> 注意:
22 +>
23 +> 两个组件系统的程序模型 (web 组件 与 react 组件) 区别在
24 +> web组件通常暴露一个命令式的API (比如 一个 `video` web 组件可能暴露 `play()`
25 +> 与 `pause()` 函数)。 因为web 组件是它们属性的声明式函数,
26 +> 他们应该可以执行, 但是如果要访问命令式API的一个web组件, 你将需要在组件上附加一个引用
27 +> 并与DOM节点直接交互。如果你在使用第三方web组件,
28 +> 我们推荐你写一个React组件作为你的web组件的封装。
29 +>
30 +> 当前,一个由web组件触发的事件可能不能准确地在React渲染树中传递。
31 +> 你将需要手动附加event handlers来在你的react组件中处理这些事件。
32 +
33 +
34 +## 在Web 组件中使用React
35 +
36 +
37 +```javascript
38 +var proto = Object.create(HTMLElement.prototype, {
39 + createdCallback: {
40 + value: function() {
41 + var mountPoint = document.createElement('span');
42 + this.createShadowRoot().appendChild(mountPoint);
43 +
44 + var name = this.getAttribute('name');
45 + var url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
46 + ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
47 + }
48 + }
49 +});
50 +document.registerElement('x-search', {prototype: proto});
51 +```
52 +
53 +## 完整样例
54 +
55 +若要查看完整样例,请参照[starter kit](/react/downloads.html)中的`webcomponents`例子。
56 +