组件 & Props

原文:https://react.docschina.org/docs/components-and-props.html




函数定义 / 类定义组件

定义组件有两种方法,用函数定义和用类定义。

用函数定义组件:

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

ReactDOM.render(
  <Welcome name="Sara" />,
  document.getElementById('example')
)

用类定义组件:

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

ReactDOM.render(
  <Welcome name="Sara" />,
  document.getElementById('example')
)

以上代码都会渲染出:


2070024-7f70afe6c86100b6.png

我们来回顾一下在这个例子中发生了什么:

    1. 我们对 <Welcome name="Sara" /> 元素调用了 ReactDOM.render() 方法。
    1. React 将 {name: 'Sara'} 作为 props 传入并调用 Welcome 组件。
    1. Welcome 组件将 <h1>Hello, Sara</h1> 元素作为结果返回。
    1. React DOM 将 DOM 更新为 <h1>Hello, Sara</h1>

注意:组件名称必须以大写字母开头。另外,组件类只能包含一个顶层标签,否则也会报错。




提取组件

我们可以将组件切分为更小的组件,比如下面一个例子,模拟了一个论坛的帖子。我们把用户个人信息(UserInfo)和帖子内容(Comment)两个组件拆分开。

{/* 
  用户信息组建,包含两个参数 name 和 intro
*/}
function UserInfo(props) {
  return (
    <div className="UserInfo">
      <div className="UserInfo-name">
        姓名:{props.user.name}
      </div>
      <div className="serInfo-intro">
        简介:{props.user.intro}
      </div>
    </div>
  );
}

function Comment(props) {
  return (
    <div className="Comment">
      {/* 
        调用 UserInfo 组件 
        UserInfo 的参数用 author 包装起来
      */}
      <UserInfo user={props.author} />
      <div className="Comment-text">
        帖子:{props.text}
      </div>
    </div>
  );
}

const comment = {
  text: '小明的帖子',
  author: {
    name: '小明',
    intro: '小明的自我介绍'
  }
};

ReactDOM.render(
  <Comment
    text={comment.text}
    author={comment.author} />,
  document.getElementById('root')
);

渲染后的网页:


2070024-5b31df1b9541592e.png

猜你喜欢

转载自blog.csdn.net/weixin_34241036/article/details/87154573