原文地址:https://facebook.github.io/react/docs/components-and-props.html
组件让您将UI拆分成独立的可重复使用的部分,并单独考虑每个部分。
在概念上,组件就像JavaScript函数。他们接受任意输入(称为“"props”),并返回应该在屏幕上显示的React元素描述。
一、Functional and Class Components
有两种方式创建组件:Functional and Class Components
1. Functional
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
此函数是一个有效的React组件,因为它接受一个单一的“props”对象参数与数据并返回一个React元素。 我们将这些组件称为“functional”,因为它们是字面上的JavaScript函数。
2. Class Components
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
二、Rendering a Component
- 组件元素可以是DOM标签,还可以是自定义的标签。
- 组件名称首字母始终为大写字母。
三、Composing Components
组件可以嵌套,重复使用。
eg:
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')
);
组件必须返回单个根元素。所以,APP组件返回的Welcome组件列表外层要包一个div元素。
四、Extracting Components
一个很好的经验法则是,如果您的UI的一部分被使用了几次(按钮,面板,头像),或者自己足够复杂(App,FeedStory,Comment),提取组件这是成为可重用组件的好办法。
五、Props are Read-Only
无论您将组件声明为函数还是类,都不能修改自己的props。
React非常灵活,但它有一个严格的规则:
All React components must act like pure functions with respect to their props.
//pure functions
function sum(a, b) {
return a + b;
}
这些函数被称为“pure functions”,因为它们不会尝试更改其输入,并且总是为相同的输入返回相同的结果。