React入门笔记 - Components & Props

195 阅读1分钟

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

Function & Class Components (函数式组件&类组件)

定义一个组件的时候,可以采用函数式,也可以采用类。比如:

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

上面这种是函数式。

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

这一种使用类来定义。效果都是一样的。

Extracting Components (提取组件)

下面是一个Comment组件,如何通过提取组件的方式来简化它?

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

先提取一个Avatar组件

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

有了Avatar这个组件之后,代码就可以优化为:

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

最初看到代码的时候,有点理不清楚,因为不知道props其实是一个对象(object)
React在启动Avatar这个组件的时候,传过去的props是{ user: {props.author} }这个对象。这个对象里面,key是user,value是{props.author};
然后Avatar里面src={props.user.avartarUrl},props.user = {props.author}。

再提取一个UserInfo组件

接下来,我们仿照上面提取Avatar组件一样,提取一个UserInfo组件。

function UserInfo(props) {
    return (
        <div className="UserInfo">
            <Avatar user={props.user} />
            <div className="UserInfo-name">{props.user.name}</div>
        </div>
    );
}

提取之后,Comment组件就可以简化成下面这样:

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

针对上面这个Comment组件,我再来捋一遍细节:

  • React call UserInfo这个component,传过去的props是{user: {props.author}}这个object;
  • React call Avatar这个component,传过去的props是{user: {props.author}}这个object;