react入门笔记

一、开发的脚手架(create-react-app)

安装脚手架:

npm install -g create-react-app

开发项目:

create-react-app hello-react

开启项目:

cd hello-react

yarn start 

二、组件

react在js文件里创造组件,通过render渲染组件,通过export导出组件。

import React, { Component } from 'react';

export default class Home extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-xs-1 col-xs-offset-11">
            <h1>Home</h1>
          </div>
        </div>
      </div>
    );
  }
}

三、动态语句

render里添加:

{ false ? "hello" : "world" }

四、通过 Props 传递数据

  • this.props

  • this.props.children

  • Typechecking With PropTypes

五、事件

src/components/Home.js

import React, { Component } from 'react';

import PropTypes from 'prop-types';

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.age = this.props.age;
  }

  onMakeOlder() {
    this.age += 3;
    console.log(this);
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-xs-1 col-xs-offset-11">
            <div>your name is {this.props.name}, your age is {this.props.age}</div>
            <button onClick={() => {this.onMakeOlder()}} className="btn btn-primary">Make me older</button>
          </div>
        </div>
      </div>
    );
  }
}

Home.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  user: PropTypes.object,
  children: PropTypes.element.isRequired
};

六、组件的 state 属性

设置和改变初始值:

  constructor(props) {
    super(props);
    this.state = {
      age: props.initialAge
    }
  }

  onMakeOlder() {
    this.setState({
      age: this.state.age + 3
    })
  }

七、react 如何更新 dom

使用虚拟DOM,对该更新的部分进行局部更新,从而达到提升整体性能的效果。

八、无状态组件

有状态组件:可以通过state设置,并且可以通过setState更新值的组件;

无状态组件:也被称为“函数式组件”,即“相同输入,相同输出”,它无状态改变(不会处理用户输入),也不会有生命周期。

引申:(react创建组件的三种写法)

1.es5写法:const App = React.createClass({...})

2.es6写法:class App extends Component {...}

3.函数式写法:

import React from 'react';

const Header = (props) => {
  return (
    <div>hello world</div>
  );
};

export default Header;

优点:不需要声明类;不需要绑定this关键字

高阶组件,hoc:(返回函数式组件)

tips:无状态组件是没有生命周期的,如果需要加上生命周期,则需要用高阶组件来处理。

九、子组件向父组件传值

父传子:直接在子组件上加参数

子传父:通过回调函数处理

无关联组件:通过redux处理,或见下节

十、组件间传值

原理:

十一、双向数据绑定

一方数据改变,另一方也会发生相应的改变。

常用于获取用户输入数据和显示用户输入数据。

十二、组件生命周期

一个组件的五个状态:

componentWillMount(){}
componentDidMount(){}
componentWillUpdate(nextProps, nextState){}
componentDidUpdate(prevProps, prevState){}
componentWillUnmount(){}


 
原文地址:https://www.cnblogs.com/bbcfive/p/10313961.html