4.3 Composing Components 构成组件

2017-04-17  本文已影响0人  人头原子弹

Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.

组件可以在他们是输出中参考其他组件,这样任何界别的具体需求都可以使用同样的组件抽象。一个按钮、一个表单、一个弹窗、一个幕布:在React应用里,通常这些都被表示为组件。

For example, we can create an App component that renders Welcome many times:

举个例子,我们创建一个通常表示Welcome的应用组件:

function Welcome(props){
 return <h1>Hello, {props.name}</h1>
}
function App(){
return (
 <div>
   <Welcome name="Sara" />
   <Welcome name="Cahal" />
   <Welcome name="Edite" />
 </div>
);
}
ReactDOM.render(
 <App />,
 document.getElementById('root')
);

Try it on CodePen.

在 CodePen 尝试一下。

Typically, new React apps have a single App component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like Button and gradually work your way to the top of the view hierarchy.

通常,新的React应用有一个最顶级的单独组件,当然,如果你整合React到现有的应用中,你也许可以自上而下的通过一个类似按钮这样的小组件并且逐步走到视图结构的顶端。

Caveat:

Components must return a single root element. This is why we added a <div> to contain all the <Welcome /> elements.

警告 

组件必须输出一个单独的根元素,这就是为什么我们要添加一个 <div> 去包裹所有 <Welcome /> 的元素。 
上一篇下一篇

猜你喜欢

热点阅读