组件 & Props

2019-01-23  本文已影响7人  SingleDiego

原文: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')
)

以上代码都会渲染出:


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

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




提取组件

我们可以将组件切分为更小的组件,比如下面一个例子,模拟了一个论坛的帖子。我们把用户个人信息(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')
);

渲染后的网页:


上一篇 下一篇

猜你喜欢

热点阅读