0 联系我
1.Java 开发技术交流 Q 群 https://jq.qq.com/?_wv=1027&k=5UB4P1T
2. 完整博客链接 http://www.shishusheng.com/
3. 个人知乎 http://www.zhihu.com/people/shi-shu-sheng-
4.gayhub https://github.com/Wasabi1234
组件可以将 UI 切分成一些独立的, 可复用的部件, 这样你就只需专注于构建每一个单独的部件.
组件从概念上看就像是函数, 它可以接收任意的输入值(称之为 "props"), 并返回一个需要在页面上展示的 React 元素.
1 函数定义 / 类定义组件
定义一个组件最简单的方式是使用 JavaScript 函数:
- function Welcome(props) {
- return <h1>Hello, {props.name}</h1>;
- }
该函数是一个有效的 React 组件, 它接收一个单一的 "props" 对象并返回了一个 React 元素.
我们之所以称这种类型的组件为函数定义组件, 是因为从字面上来看, 它就是一个 JavaScript 函数.
你也可以使用 ES6 class 来定义一个组件:
- class Welcome extends React.Component {
- render() {
- return <h1>Hello, {this.props.name}</h1>;
- }
- }
上面两个组件在 React 中是相同的.
我们将在 [下一节] 讨论类的一些额外特性. 在那之前, 我们都将使用较为简洁的函数定义组件.
2 组件渲染
- function formatDate(date) {
- return date.toLocaleDateString();
- }
- 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>
- );
- }
- const comment = {
- date: new Date(),
- text: 'I hope you enjoy learning React!',
- author: {
- name: 'Hello Kitty',
- avatarUrl: 'http://placekitten.com/g/64/64'
- }
- };
- ReactDOM.render(
- <Comment
- date={comment.date}
- text={comment.text}
- author={comment.author} />,
- document.getElementById('root')
- );
- function Avatar(props) {
- return (
- <img className="Avatar"
- src={props.user.avatarUrl}
- alt={props.user.name}
- />
- );
- }
来源: http://www.jianshu.com/p/fa863698fcbc