React 学习篇 (三)

Components and Props这一篇干货还是挺多的

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

// You can also use an ES6 class to define a component:

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

第一种叫function component,可以带参数,返回的是一个React element

组件渲染

App.js少做修改,代码如下,以这个Demo理解一下文档所讲的内容吧。

const comment = {
  date: new Date(),
  text: 'I hope you enjoy learning React!',
  author: {
    name: 'Hello Kitty',
    avatarUrl: 'https://placekitten.com/g/64/64',
  },
};

class App extends Component {

  render() {
    return (
      <div className="App">
        <div className="UserInfo">          
          <img className="UserInfo-Avatar" src={comment.author.avatarUrl} alt={comment.author.name} />
          <div className="UserInfo-AuthorName">{comment.author.name}</div>
        </div>
        <div className="Comment-Text">{comment.text}</div>
        <div className="Comment-Date">{comment.date.toLocaleDateString()}</div>
      </div>
    );
  }

}

Note: Always start component names with a capital letter.
React treats components starting with lowercase letters as DOM tags. For example, <div /> represents an HTML div tag, but <Welcome /> represents a component and requires Welcome to be in scope.

看文档的时候多注意一下这种note,这里包含的信息还是挺多的,我们创建自定义的组件时,记得一定要首字母大写,如 class 后边的App,系统帮我们创建的时候都这么搞了,我们没理由不模仿。

You can read more about the reasoning behind this convention here.

Extracting Components(提炼组件)

文档在这一段刚开始有句话,是这样说的:Don’t be afraid to split components into smaller components.
大体意思就是说别害怕拆分组件

为什么要提炼组件呢,这体现了封装思想以及代码风格。在小项目里可能我们代码量不是很大,一些重复代码一坨一坨在一起体现不出来,但是当我们项目逐渐打起来以后,一个很好的编码风格能帮我们省去很多不必要的麻烦。

class App extends Component {

  render() {
    return (
      <div className="App">        
        <UserInfo user={comment.author}/>
        <CommentText text={comment.text}/>
        <CommentDate date={comment.date}/>
      </div>
    );
  }

}
class UserInfo extends Component {
    render() {
        return (
            <div className="UserInfo">
                <img className="UserInfo-Avatar" src={this.props.user.avatarUrl} alt={this.props.user.name} />
                <div className="UserInfo-AuthorName">{this.props.user.name}</div>
            </div>
        )
    }
}

我们知道userInfo标签部分,显示的都是用户信息,那么我们将之提炼拆分出来,那么这个组件只需要考虑用户信息了,清晰明了,达到一个解耦的作用,并且复用起来也很高效,不至于说在其他地方再写一遍重复的代码。

Props are Read-Only

拆分组件过程中我们用到了props,我们看App中,<div />标签下 我拆分了三个 子组件,既然有 子组件 当然 App 就是父组件了,那么组件是怎么通信的呢?以UserInfo为例:我们通过对user属性赋值,在子组件中使用props来接收父组件传过来的值。ok,这就是props的作用。对props的理解目前还不深,后续学习过程中再逐渐增加对他的理解描述吧!!!

猜你喜欢

转载自blog.csdn.net/weixin_34253539/article/details/87640800