React学习笔记 - 组件&Props

React Learn Note 4

React学习笔记(四)

标签(空格分隔): React JavaScript


三、组件&Props

组件可以将UI切分成一些独立的、可复用的部件,这样你就只需专注于构建每一个单独的部件。

组件接收props,返回react元素。

1. 函数定义\类定义组件

最简单组件方式 - 函数定义组件

// 函数定义组件
function Welcome(props) {
    return <h1>Hello, {props.name}!</h1>;
}

ES6 class定义组件,效果同上:

// ES6 class定义组件
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}!</h1>;
    }
}

2. 组件渲染

将组件作为React元素,标签的属性作为props键值:

const element5_1 = <Welcome name="Sara"></Welcome>;
ReactDOM.render(
    element5_1,
    document.getElementById('root5')
);
**警告:** 组件名称必须大写字母开头。

3. 组合组件

React组件也可以嵌套。

function App() {
    return (
        <div>
            <Welcome name="Bob"></Welcome>
            <Welcome name="Cahal"></Welcome>
            <Welcome name="John"></Welcome>
        </div>
    );
}

ReactDOM.render(
    <App></App>,
    document.getElementById('root6')
);

图1

**警告:** 组件的返回值只能有一个根元素。所以将多个`Welcome`元素用`div`包裹。

4. 提取组件

可以将组件切分为更小的组件。

function formatDate(date) {
    return date.toLocaleTimeString();
}
function Comment(props) {
    return (
      <div className="Comment">
          <div className="UserInfo">
              <img 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>
    );
}

ReactDOM.render(
    <Comment author={{avatarUrl: '../static/img/zhifibao_key.jpg', name: 'Jessie'}} text="This is comment text." date={new Date()}></Comment>,
    document.getElementById('root7')
);

图2

这个组件接收author(对象)、text(字符串)、以及date(Date对象)作为props。是个复杂的组件。接下来我们提取拆分这个组件。

首先提取Avatar组件:

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

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

// 最终Comment组件被简化为
function Comment2(props) {
    return (
        <div className="Comment">
            <UserInfo user={props.author}></UserInfo>
            <div className="Comment-text">
                {props.text}
            </div>
            <div className="Comment-date">
                {formatDate(props.date)}
            </div>
        </div>
    );
}

ReactDOM.render(
    <Comment2 author={{avatarUrl: '../static/img/zhifibao_key.jpg', name: 'Xiaoyu Lee'}} text="Wow, this is very beautiful." date={new Date()}></Comment2>,
    document.getElementById('root8')
);

5. Props的只读性

无论是使用函数或是类来声明一个组件,它决不能修改它自己的props。

The end...    Last updated by: Jehorn, Jan 07, 2018, 5:44 PM

posted @ 2018-01-07 17:45  古宝只  阅读(1709)  评论(0编辑  收藏  举报