React 基本概念总结(二)

React 初探

Posted by Nicodechal on 2018-06-27

Components and Props

函数式组件和类组件

函数式组件的例子:

1
2
3
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

类组件使用 ES6 的 class 语法创建 React 组件:

1
2
3
4
5
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

class 语法的 React 组件会有一些额外的特性,之后会进行介绍。

渲染一个组件

当使用 jsx 语法渲染一个自定义组件时,其属性会被整合成一个对象传递给组件,该对象可以称为 props。

下面的代码是一个自定义组件的定义和使用 jsx 渲染该组件的示例:

1
2
3
4
5
6
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(element, document.getElementById("root"));

上面的 Welcome 组件有一个 props 参数,从该参数可以获得传递到组件的属性。

提取组件

尽量将组件划分为更小的组件,下面用一个例子说明。

下面是一个 Comment 组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img
className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">{props.author.name}</div>
</div>
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">{formatDate(props.date)}</div>
</div>
);
}

接收的 props 包括 author 对象、text 字符串和 date 日期。

根据嵌套关系可以先划分出 Avatar 组件:

1
2
3
4
5
function Avatar(props) {
return (
<img className="Avatar" src={props.user.avatarUrl} alt={props.user.name} />
);
}

然后 Comment 组件可以写为:

1
2
3
4
5
6
7
8
9
10
11
12
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} />
<div className="UserInfo-name">{props.author.name}</div>
</div>
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">{formatDate(props.date)}</div>
</div>
);
}

接着可以抽出 UserInfo 组件:

1
2
3
4
5
6
7
8
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">{props.user.name}</div>
</div>
);
}

这样 Comment 组件会变得更简洁:

1
2
3
4
5
6
7
8
9
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">{props.text}</div>
<div className="Comment-date">{formatDate(props.date)}</div>
</div>
);
}

最后要注意 props 是只读的,不应该修改 props 的值。