react base

内容纲要

使用create-react-app官方脚手架

1) 安装create-react-app

npm i -g create-react-app

2) 创建项目

create-react-app react-demo

创建后cd到项目根目录。

此时的项目结构如下:

react-demo
    + node_modules
    + public
    |   -- favicon.ico
    |   -- index.html
    |   -- mainfast.json
    + src
    |   -- App.css
    |   -- App.js
    |   -- App.test.js
    |   -- index.css
    |   -- index.js
    |   -- logo.svg
    |   -- registerServiceWorker.js
    + -- .gitignore
    + -- package.lock.json
    + -- package.json
    + -- README.md

3) 启动项目(进入项目文件夹中)

npm start

4) 编译打包项目

npm build

组件

1) 在public/index.html中引入ui框架

2) 在src中创建components文件夹

3) 在components中创建Home.js文件

import React,{Component} from 'react'

export default class Home extends Component{
  constructor() {
    super()
    console.log('home constructor init.')
  }
  render() {
      return (
        <header className='container' id='home'>
          <div className='row'>
            <div className='col-md-4 col-md-offset-4'>
              <div>home</div>
            </div>
          </div>
        </header>
      )
  }
}

4) 在App.js中导入Home.js:

import Home from './components/Home'

并修改App.js中的render方法:

<Home></Home>

5) 查看浏览器自动更新后的显示

props数据传递

1) 声明临时使用变量

let dataset = {
  name:'indeex',
  email:'indeex@qq.com',
  num:1
}

2) 给子组件添加属性

<Home info={dataset} test='测试'></Home>

3) 给Home节点添加子节点

<Home info={dataset} test='测试'>
  <div>Home's children.</div>
</Home>

4) 在子组件中绑定数据显示

<div>home</div>
<p>{this.props.test}</p>
<p>{this.props.info.name}</p>
<p>{this.props.info.num}</p>
<div>{this.props.children}</div>

5) 给子组件添加类型检测

import PropTypes from 'prop-types'

Home.propTypes = {
  test:PropTypes.string,
  info:PropTypes.object,
  children:PropTypes.element.isRequired
}

6) 修改父组件(App)中的临时数据为正式数据

事件

1) 在构造函数中声明事件操作变量

this.num = this.props.info.num;

2) 创建事件

clickHandler(e){
    console.log('clicked.',this)
    this.num = this.num + 3
    console.log(this.num)
}

3) 添加显示

<p className='text-success'>{this.num}</p>

4) 添加事件按钮

<button className='btn btn-success' onClick={() => this.clickHandler()}>add</button>

注意
由于react取消了自动绑定,onClick={this.clickHandler}无法被触发。
也可以使用onClick={this.clickHandler.bind(this)}

5) 查看控制台

this.num已经正常增加,但是页面并没有更新,需要state对其显示组件进行更新

state更新组件显示

1) 修改事件操作变量

// this.num = this.props.info.num;
this.state = {
  num:props.info.num
}

2) 修改事件改变量

// this.num = this.num + 3
this.setState({
  num:this.state.num + 3
})

3) 修改所有this.numthis.state.num

<p className='text-success'>{this.state.num}</p>

无状态组件

1) 无状态组件

使用场景

  • 没有用户输入,无state
  • 无需生命周期

优点

  • 无需声明类,无继承,减少开销
  • 无需强制绑定this

2) 在components文件夹下创建无状态组件Header.js

3) 在Header.js中导入react

import React from 'react'

4) 声明变量Header

const Header = (props) =>{
  return (
    <section id='head' className='container'>
      <div className='row'>
        <div className='col-md-4'>head</div>
      </div>
    </section>
  )
}

export default Header

注意
声明变量不需要使用render方法
不能直接导出const声明的变量

子组件向父组件传值

1) 在父组件中添加方法

appClickHandler(data){
    console.log('appClickHandler.',data)
}

2) 给Home节点添加属性

<Home info={dataset} test='测试' click={this.appClickHandler}>
  <div>Home's children.</div>
</Home>

3) 在子组件中添加方法

sendClickHandler(){
    this.props.click(this.state.num);
}

4) 添加触发按钮

<button className='btn btn-success' onClick={() => this.sendClickHandler()}>send App btn</button>

5) 点击add按钮,再点击send App btn,数据会从子组件传递给父组件

组件间传值

1) 增加App构造函数

constructor(){
    super()
  }

2) 增加需要改变的state

this.state = {
  homeShowData:'This is home.'
}

3) 给Head元素添加属性

<Head homeShow={this.state.homeShowData}></Head>

4) 给Header子组件添加显示

{props.homeShow}

此时Header子组件会显示:This is home.

5) 给APP组件添加需要改变状态的方法

changeHeaderShow(data){
    this.setState({
      homeShowData:data
    })
}

6) 给Home元素添加属性

<Home info={dataset} test='测试' click={this.appClickHandler}  chageClickHander={this.changeHeaderShow.bind(this)}>

7) 给Home组件添加状态值

homeShowData:'A! I am changed.Now Is not home.'

8) 给Home组件添加方法

changeHeaderShow(){
    this.props.chageClickHander(this.state.homeShowData)
}

9) 添加改变Header组件数据的方法

<button className='btn btn-success' onClick={() => this.changeHeaderShow()}>change Header show</button>

10) 点击Home组件中的change Header show按钮,Header组件中的数据会改变为Home组件中的数据

双向数据绑定

1) 给Home元素添加属性

<Home info={dataset} test='测试' click={this.appClickHandler}  chageClickHander={this.changeHeaderShow.bind(this)} initData={this.state.homeShowData}>
  <div>Home's children.</div>
</Home>

2) 给Home组件添加方法

changeHandler(e){
    console.log(e.target.value)
    this.props.chageClickHander(e.target.value)
    this.setState({
      homeShowData:e.target.value
    })
}

3) 添加输入框

<input className='text-warning form-control' defaultValue={this.props.initData} onChange={(e) => this.changeHandler(e)}/>

组件生命周期

1) 组件三种状态

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

2) 生命周期的方法

  • componentWillMount 在渲染前调用,在客户端也在服务端。

  • componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI)。

  • componentWillReceiveProps 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。

  • shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
    可以在你确认不需要更新组件时使用。

  • componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。

  • componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用。

  • componentWillUnmount在组件从 DOM 中移除的时候立刻被调用。

3) 可使用chrome插件查看rendering

当然,这些基础在官网都有很好的例子。

code enjoy! ◐‿◑

作者:indeex

链接:http://indeex.cc

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


发表评论

您的电子邮箱地址不会被公开。