React實戰(zhàn)入門指南

基礎入門文檔建議直接查看React中文文檔,這樣能少走很多彎路,基于版本V16.6.0
React中文文檔

重點:推薦在 React 中使用 JSX 來描述用戶界面。[JSX 簡介]

生命周期

1.組件初始化階段

constructor(props) {
    super(props);
    this.state = {date: new Date()};
}

super(props)用來調(diào)用基類的構造方法( constructor() ), 也將父組件的props注入給子組件,供子組件讀取(組件中props只讀不可變,state可變)。而constructor()用來做一些組件的初始化工作,如定義this.state的初始內(nèi)容。
2.組件的掛載階段
componentWillMount
1、組件剛經(jīng)歷constructor,初始完數(shù)據(jù)
2、組件還未進入render,組件還未渲染完成,dom還未渲染
componentDidMount
組件第一次渲染完成,此時dom節(jié)點已經(jīng)生成,可以在這里調(diào)用ajax請求,返回數(shù)據(jù)setState后組件會重新渲染
render
render函數(shù)會插入jsx生成的dom結構,react會生成一份虛擬dom樹,在每一次組件更新時,在此react會通過其diff算法比較更新前后的新舊DOM樹,比較以后,找到最小的有差異的DOM節(jié)點,并重新渲染
3.更新階段
shouldComponentUpdate
此方法通過比較nextProps,nextState及當前組件的this.props,this.state,返回true時當前組件將繼續(xù)執(zhí)行更新過程,返回false則當前組件更新停止,以此可用來減少組件的不必要渲染,優(yōu)化組件性能。
優(yōu)化:利用shouldComponentUpdate鉤子函數(shù)優(yōu)化react性能

shouldComponentUpdate(nextProps,nextState){
    if(nextState.msg == this.state.msg){
      console.log(132312);
      return false;
    }else{
      return true;
    }
}

componentWillReceiveProps
此方法只調(diào)用于props引起的組件更新過程中,參數(shù)nextProps是父組件傳給當前組件的新props。但父組件render方法的調(diào)用不能保證重傳給當前組件的props是有變化的,所以在此方法中根據(jù)nextProps和this.props來查明重傳的props是否改變,以及如果改變了要執(zhí)行啥,比如根據(jù)新的props調(diào)用this.setState出發(fā)當前組件的重新render
componentWillUpdate
此方法在調(diào)用render方法前執(zhí)行,在這邊可執(zhí)行一些組件更新發(fā)生前的工作,一般較少用。
componentDidUpdate
此方法在組件更新后被調(diào)用,可以操作組件更新的DOM,prevProps和prevState這兩個參數(shù)指的是組件更新前的props和state

4.卸載階段
componentWillUnmount
此方法在組件被卸載前調(diào)用,可以在這里執(zhí)行一些清理工作,比如清楚組件中使用的定時器,清楚componentDidMount中手動創(chuàng)建的DOM元素等,以避免引起內(nèi)存泄漏。

父子之間的傳遞屬性

1.不使用redux
父傳子
子組件顯示父組件傳過來的props有兩種方式:
1、直接使用
這種方式,父組件改變props后,子組件重新渲染,由于直接使用的props,所以我們不需要做什么就可以正常顯示最新的props

class Child extends Component {
    render() {
        return <div>{this.props.someThings}</div>
    }
}

2、轉(zhuǎn)換成自己的state
這種方式,由于我們使用的是state,所以每當父組件每次重新傳遞props時,我們需要重新處理下,將props轉(zhuǎn)換成自己的state,這里就用到了 componentWillReceiveProps。

class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
            someThings: props.someThings
        };
    }
    componentWillReceiveProps(nextProps) {  //只有添加此方法才會更新父頁面?zhèn)鬟^來的參數(shù)
        this.setState({someThings: nextProps.someThings});
    }
    render() {
        return <div>{this.state.someThings}</div>
    }
}

子傳父

import React, { Component } from 'react';
import Children from './Children';
class Father extends Component {
  childs = (txt) => {
    console.log(txt)
  }
  render() {
    return (
      <div className="box">
        <Children name="我是父級傳遞過來的" childs={this.childs} fun={this.fun}></Children>
      </div>
        );
  }
}
export default Father;
import React, { Component } from 'react';
class Children extends Component{
    giveFather=()=>{
        const value='你想要傳的值'
        this.props.childs(value)
    }
    render(){
        let str = "我是子組件內(nèi)的內(nèi)容";
        return (
            <div className="child">
               {this.props.name}
               <button onClick={this.giveFather}>button</button>
            </div>
        )
    }
}
export default Children;

2.使用redux(狀態(tài)管理): redux中文官網(wǎng)

事件處理

綁定this:

class LoggingButton extends React.Component {
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

或者

class LoggingButton extends React.Component {
  handleClick (val) {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.update.bind(this,{name:'111'})}>
        Click me
      </button>
    );
  }
}

通常我們會為事件處理程序傳遞額外的參數(shù),建議選中bind綁定的方式,第一個參數(shù)固定為this,參數(shù) e 作為 React 事件對象將會被作為第二個參數(shù)進行傳遞。

修改state為對象中的某一個屬性值

針對state為對象,想要修改對象中某一個值而不修改其他值

import React, { Component } from 'react'
import Child from '../components/index'

export default class index extends Component {
  constructor(props){
    super(props);
    this.state = {
      msg:'我是從父組件傳過來的18',
      json:{
        msg:'chen ll',
        name:'chen ll'
      }
    }
  }
  update(){
    let data = Object.assign({}, this.state.json, { msg: '2222' })
    this.setState({json: data})
    console.log(this.state.json)
  }
  render() {
    return (
      <div>
        <Child msg={this.state.msg} childs={this.childs}></Child>
        {this.state.json.msg}
        <button onClick={this.update.bind(this)}>11111111</button>
      </div>
    )
  }
}
組件的隱藏

原理:通過display元素控制

import React, { Component } from 'react'
import Child from '../components/index'

export default class index extends Component {
  constructor(props){
    super(props);
    this.state = {
      msg:true,
      json:{
        msg:'chen ll',
        name:'chen ll'
      }
    }
  }
  update(){
    this.setState(prevState => ({
      msg: !prevState.msg
    }));
  }
  render() {
    return (
      <div>
        <Child msg={this.state.msg}></Child>
        <button onClick={this.update.bind(this)}>11111111</button>
      </div>
    )
  }
}

Child組件

import React, { Component } from 'react'

export default class index extends Component {
    constructor(props){
        super(props);
        this.state = {
            msg : props.msg
        }
    }
    componentWillReceiveProps(nextProps) {
        this.setState({msg: nextProps.msg});
    }

    render() {
        return (
        <div style={{'display':this.state.msg?'block':'none'}}>
            22222222
        </div>
        )
    }
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容