React

目录

1.react生命周期

 2.父传子(class)

 3.父传子(function)

 4.子传父(class)

 5.跨组件传值(class & function)

 6.setState(class )

 7.ref(class)获取DOM元素

 8.ref(function)获取DOM元素

 9.Css in js

 10.axios基本使用

 11.过度动画和纯函数使用


1.react生命周期

 // 挂载时调用
  componentDidMount() {
    console.log('componentDidMount方法')
     // 此方法适用于发送网络请求(官方建议)
     // 也可以添加一些订阅(会在componentWillUnmount(销毁时)取消订阅)
  }

  // 更新时调用
  componentDidUpdate() {
    console.log('componentDidUpdate方法')	
      // 当组件更新后,可以在此处对DOM进行操作;
	  // 如果你对更新前后的props进行了比较,也可以选择在此处进行网络请求;(例如,当props未发生变化时,则不会执行网络请求)。
  }

  // 销毁时调用
  componentWillUNmount() {
    // 在此方法中执行必要的清理操作
    // 列如:定时器,componentDidMount()中创建的订阅等。
  }

 2.父传子(class)

import React from 'react'

// 父组件
export default class Dpp extends React.Component{
  constructor(){
    super()
    this.state = {
      isShow:'父组件的数据'
    }
  }

  render(){
    const {isShow} = this.state
    return(
      <div>
        <Ass isShow={isShow}/>
      </div>
    )
  }
}

// 子组件
class Ass extends React.Component{
  constructor(props){
    super(props)
    this.state={
      data:props.isShow
    }

  }

  render(){
    const {data} = this.state
    // const {isShow} = this.props
    return(
      <div>
        <p>数据:{ data }</p>
      </div>
    )
  }
}

 3.父传子(function)

// 父组件
export function Lpp(){
  
  const data = [
    {name:'(fun)父组件的数据',age:15},
    {name:'(fun)父组件null',age:18},
  ]
  return( 
    <div>
      <Kpp data={data}/>
    </div>
  )
}

// 子组件
function Kpp(props){
  console.log(props);
  return(
    <div>
      <p>(fun组件)数据:{props.data[1].name}</p>
    </div>
  )
}

 4.子传父(class)

// 父组件
import React, { Component } from 'react';
import App from './App'

export default class index extends Component {
  state = {
    titles: ['新歌', '精选', '流行', 'new'],
    aticon: 'aticon',
    data:'新款'
  }
  render() {
    const { titles, aticon ,data} = this.state;
    return (
      <div>
        <App titles={titles} ads={ i => this.ads(i)} aticon={aticon} />
        <h1>{data}</h1>
      </div>
    );
  }
  ads(index){	// 接受子组件传过来的索引参数
    console.log(index);
    const {titles} = this.state
    this.setState({
      data:titles[index]	// 根据索引参数来显示对应的数组
    })
  }
}



// 子组件
import React, { Component } from 'react';
import propTypes from 'prop-types'

export default class App extends Component {
  state={
    lei:0
  }
  render() {
    const {titles,aticon} = this.props
    const {lei} = this.state
    return (
      <div id="titles">
        {
          titles.map((item,index) => {
            return (
              <div key={index} 
                   id='titl' 
                   className={index === lei ? aticon:''} 
                   onClick={e => this.itemClick(index)}>
                     <span>{item}</span>
              </div>
            )
          })
        }
      </div>
    );
  }
  itemClick(index){
    this.setState({
      lei:index
    })
    this.props.ads(index) // 把index传去父组件
  }
}

// 类型限制
App.propTypes ={
  titles:propTypes.array.isRequired
}

 5.跨组件传值(class & function)

import React, { Component } from 'react'

const Initialvalue = {	// 默认值
  name: '--------!!!'	
}
const Consumers = React.createContext(Initialvalue)

// 父组件
export default class NewContext extends Component {
  state = {
    name: 'chen zhan hong'
  }
  render() {
    return (
      <div>
        <Consumers.Provider value={this.state}>
          <h1>父组件:{this.state.name}</h1>
          <NewContextZi />
        </Consumers.Provider>
      </div>
    )
  }
}

// 子组件
class NewContextZi extends Component {
  render() {
    return (
      <Consumers.Consumer>
        {
          vla => {
            return (
              <div>
                <h2>子组件:{vla.name || 0}</h2>
                <NewContextSUN />
              </div>
            )
          }
        }
      </Consumers.Consumer>
    )
  }
}

// 孙组件
class NewContextSUN extends Component {
  render() {
    console.log(this);
    return (
      <div>
        <h3>孙组件:{this.context.name}</h3>
        <NewContextZengSUN />
      </div>
    )
  }
}

NewContextSUN.contextType = Consumers

// 曾孙组件
function NewContextZengSUN(props) {
  return (
    <Consumers.Consumer>
      {
        vla => {
          console.log(vla);
          return (
            <h4>曾组件:{vla.name || 0}</h4>
          )
        }
      }
    </Consumers.Consumer>
  )
}

 6.setState(class )

import React, { Component } from 'react'

export default class App extends Component {
  state = {
    data: 0
  }
  render() {
    return (
      <div>
        <h1>{this.state.data}</h1>
        <button onClick={() => this.dianjin()}>+1</button>
      </div>
    )
  }
  dianjin() {
      // setState(更新数据, 回调函数)
      // setState是异步的
    this.setState({
      data: this.state.data + 1
    }, e => {
      console.log(this.state.data);	// 拿到更新之后的值
    })
  `dianjin() {
      // propsState 更新之前的值
    this.setState((propsState,p) => ({data:propsState.data+1}))
  }`
  }
}

 7.ref(class)获取DOM元素

import React, { PureComponent,createRef } from 'react'

class Cevent extends PureComponent {
  titleREF = createRef();
  titFunRef = null;

  render(){
    return(
      <div>
         {/* ref是拿到DOM元素的 */}
        <p ref = 'czh'>Cevent</p>
        <p ref = { this.titleREF } >Cevent</p>
        <p ref = { e => this.titFunRef = e }>Cevent</p>
        <button onClick={() => this.Evenetsemit()}>点击了Cevent</button>
      </div>
    )
  }
  Evenetsemit(){
      {/* 使用方式一:字符串方式(官方不推荐使用,后期会废气掉)*/}
    this.refs.czh.innerHTML = 'hello'
      {/* 使用方式二:对象方式(目前官方推荐使用)*/}
    this.titleREF.current.innerHTML = 'hello createRef'
      {/* 使用方式三:回调函数方式*/}  
    this.titFunRef.innerHTML = 'hello FunRef'
    console.log(this.refs.czh);
  }
}

 8.ref(function)获取DOM元素

import React, { forwardRef, PureComponent, createRef} from 'react'


export default class Ref extends PureComponent {
  createRefs = createRef()
  render() {
    const cnm = () => {
      return (e) => {
        console.log(this.createRefs.current);
      }
    }
    return (
      <div>
        <Context ref={this.createRefs} />
        <button onClick={cnm(this)}>打印ref</button>
      </div>
    )
  }
}

export const Context = forwardRef(
  (props, ref) => {
    console.log(props);
    return (
      <div>
        <p id='ss' ref={ref}>Context</p>
      </div>
    )
  }
)

 9.Css in js

// 第一种
<p style={{fontSize:"18px",color:"red"}}>内联样式</p>


// 第二种
const styles = {
        fontSize:"18px",
        color:this.state.style
    }
return(
	<p style={styles}>动态内联样式</p> 
)


// 第三种:创建一个App.module.css样式文件并引入
App.module.css
	.nameclass{
     	color:'red'  
    }
App.module.css

impot AppStyle from './App.module.css'

render(){
 return(
 	<div>
        <p className = {AppStyle.nameclass}>module.css样式</p>
    </div>
 )   
}

// 第四种 CSS in js
yarn add styled-components
vscode-styled-components vscode安装这个代码提示插件
import styled from 'styled-components'
const Styless = styled.div`
	color: red;
	font-size: 18px;
`

 10.axios基本使用

componentDidMount(){
    // get
    axios({
      url:'http://www.httpbin.org/get',
      params:{
        name:'浪白',
        age:18
      }
    })
    .then(d => console.log(d))
    .catch(e => console.log(e))

    // post
    axios({
      url:'http://www.httpbin.org/post',
      data:{
        name:'post浪白',
        age:19
      },
      method:'post'

    })  
    .then( d => console.log(d))
    .catch( e => console.log(e))
    
    axios.get('http://www.httpbin.org/get',{
      params:{
          name:'czh',
          age:20
      }
    }).then(e => console.log(e))
    .catch(e => console.log(e))
    
    axios.post('http://www.httpbin.org/post',
      {
        name:'czh-post',
        age:20
      }
    ).then(e => console.log(e))
    .catch(e => console.log(e))
  }


// 此代码代替上面代码(建议使用这个)
// async (异步)	await (等待)
// try是检测错误 catch是拿到检测的错误信息
// 使用await的前提得是在async里面 列如下面代码
 async componentDidMount(){
   try{
 	const result = await axios.post('http://www.httpbin.org/post',
      {
        name:'czh-post',
        age:20
      }
    )
 	console.log(result)//拿到数据
    }catch(err){
      console.log(err);//拿到错误
    }
}

 11.过度动画和纯函数使用

yarn add react-transition-group

react-transition-group主要包含四个组件:

Transition
	口该组件是一个和平台无关的组件(不一定要结合CSS ) ;
	在前端开发中,我们一般是结合CSS来完成样式,所以比较常用的是

CSSTransition 
	在前端开发中,通常使用CSSTransition来完成过渡动画效果

SwitchTransition
	两个组件显示和隐藏切换时,使用该组件TransitionGroup
	将多个动画组件包裹在其中,一般用于列表中元素的动画;

TransitionGroup
    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值