初识React-Components

Component and Props

component把整个应用分割成独立的、可重复使用的部分;

Component有两种方式:函数式和类式

最简单的方式是函数式(函数名首字母必须大写)
创建 Comment 组件,它将依赖于从父级传来的数据。从父级传来的数据在子组件里作为 '属性' 可供使用。

function Formatter(props) {
        return <h1>{props.firstName +' '+props.lastName}</h1>;
    }
//这是一个有效的React 组件,因为它接受了一个props(代表properties)数据对象并且返回了一个React 组件。因为它与Javascript函数,所有我们把这类组件称之为’函数式组件‘

es6 类的方式定义组件

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

渲染组件

component既可以是DOM标签也可以是使自定义的标签(首字母必须大写);

组合组件->一个组件涉及其他的组件

function App() {
        return (<div>
            <Welcome name="学习1"></Welcome>
            <Welcome name="学习2"></Welcome>
            <Welcome name="学习3"></Welcome>
            <Welcome name="学习4"></Welcome>
        </div>)
    }

    ReactDOM.render(<App/>,document.getElementById('b_com'));
//使用App组件渲染多次Welcome组件

拆分组件

通常在一个应用程序中只有一个顶层的组件;如果想整和一个项目,应该从最小的组件开始着手;

首先考虑一个评论组件(Comment Component)

1.原始代码:

function formatDate(date) {
        return date.toLocaleDateString();
    }
    function Comment(props) {
        return (
          <div className="Comment">
              <div className="UserInfo">
                  <img className="Avatar" src={props.author.avatarUrl} alt=""/>
                  <div className="user-name">
                      {props.author.name}
                  </div>
              </div>
              <div className="text">
                  {props.text}
              </div>
              <div className="date">
                  {formatDate(props.date)}
              </div>
          </div>
        );
    }

    const com_ele = {
        date: new Date(),
        text: 'I hope you enjoy learning React!',
        author: {
            name: 'Hello Kitty',
            avatarUrl: './img/0.jpg'
        }
    }
    ReactDOM.render(<Comment
    author={com_ele.author}
    date={com_ele.date}
    text={com_ele.text}
    />,document.getElementById('com'));

//首先拆分头像
function Avatar(props) {
        return (<img className="Avatar"
                     src={props.user.avatarUrl}
                     alt={props.user.name}
        />);
    }
//拆分用户信息
function Comment(props) {
        return (
                <div className="Comment">
                    <UserInfo user={props.author}/>
                    <div className="text">
                        {props.text}
                    </div>
                    <div className="date">
                        {formatDate(props.date)}
                    </div>
                </div>
        );
    }
function UserInfo(props) {
        return (
                <div className="UserInfo">
                    <Avatar user={props.user} />
                    <div className="user-name">
                        {props.user.name}
                    </div>
                </div>
        )
    }
    function Avatar(props) {
        return (<img className="Avatar"
                     src={props.user.avatarUrl}
                     alt={props.user.name}
        />);
    }

按照官网例子写的

只读props;props 是不可变的:它们从父级传来并被父级“拥有”。

如果我们从服务端获取数据,我们将一处数据的prop,用获取数据的url替换;

State和它的生命周期

按照上一个章节,时钟的组件,应该是时钟组件自己一直在更新,而不是通过定时进行更新;为了实现自我更新,这次我们使用他里面的‘state ’
前面有提到定义组件有两种方式,函数式和类。把组件定义成类有些特殊的属性。state就是她特殊的属性,所以接下来我们要把函数式转换成类

1.定义ES6类,继承React.Component;
2.添加一个空的render();
3.把原来函数体里面的内容,复制到render()函数里面;把里面的this.props.date用this.state.date替换掉;
4.在render()里,用this.props替换props;
5.删除空的函数;

class Clock extends React.Component {
        constructor (props){//构造函数初始化自身的属性
         super(props);//子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
         this.state = {date:new Date()};
        }
        render() {
            return (
                    <div>
                        <h1>Hello, world!学习state</h1>
                        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
                    </div>
            )
        }
    }

如何让时钟一直动态更新
1.在类里面新增生命周期函数
应用程序中有很多的组件,当他们被销毁的时候,释放的资源是很重要的
在时钟第一次渲染的时候,我们就像设置一个定时,这在react中叫做‘mounting;当时钟组件被移除的时候,我们需要清空这个定时,这个在react中叫做‘unmounting’,这两个过程就形成了生命周期

class Clock extends React.Component {
        constructor (props){
         super(props);
         this.state = {date:new Date()};
        }

        componentDidMount(){//3.dom插入时钟输出时,React会调用此函数,然后调用一个定时,每秒更新一次,
            this.timerID = setInterval(()=>this.trick(),1000)
        }

        componentWillUnmount(){
            clearInterval(this.timerID);
        }

        trick() {
            this.setState({//4.setState每秒更新视图
                date: new Date()
            });
        }

        render() {//2.Clock执行render时,会把dom元素渲染出来
            return (
                    <div>
                        <h1>Hello, world!学习state</h1>
                        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
                    </div>
            )
        }
    }

    ReactDOM.render(<Clock/>,document.getElementById('clock'));//1.当Clock通过React.render()时,Clock组件会执行它的构造函数,进而会初始化this.state;

state不直接更新视图
重新渲染使用setState,this.state只在构造函数初始化一次
state更新可能是异步
react可能批量处理多个setState();来更新某一个状态
因为 this.state和this.props可能是异步更新,所以不应该使用它们的值来计算下一个状态
eg:this.setState({ counter: this.state.counter + this.props.increment, });
修改上一个错误代码。利用setState()接受一个函数作为参数,而不是对象;该函数的第一个参数是以前state的值,在更新时使用的props数据作为第二个参数
eg:this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本笔记基于React官方文档,当前React版本号为15.4.0。 1. 安装 1.1 尝试 开始之前可以先去co...
    Awey阅读 7,805评论 14 128
  • 个人笔记, 转载请注明转载自 szhshp的第三边境研究所 Refs and the DOM In the t...
    szhielelp阅读 1,503评论 0 1
  • Learn from React 官方文档 一、Rendering Elements 1. Rendering a...
    恰皮阅读 2,688评论 2 3
  • 以下内容是我在学习和研究React时,对React的特性、重点和注意事项的提取、精练和总结,可以做为React特性...
    科研者阅读 8,297评论 2 21
  • 使用 create-react-app 快速构建 React 开发环境 项目的目录结构如下: React JSX ...
    majun00阅读 522评论 0 0