116.《React基础知识总结大全》

本文概述了React的基础知识,包括阻止默认行为、组件间父子及兄弟间的值传递,规则校验,生命周期管理,componentDidUpdate中的常见问题,高阶组件(enderprops模式和封装)、路由设置,以及createContext进行跨组件值传递。
摘要由CSDN通过智能技术生成

react 基础知识总结

01.阻止默认行为

export default class Index extends Component {
    handleClick(e){
        e.preventDefault()
        console.log("触发了");
    }
    render() {
        return (
            <div>
               <a href="http://www.baidu.com" onClick = { this.handleClick }>单击</a>
            </div>
        )
    }
}

02.组件传值

1.父向子

// 父组件
export default class Index extends React.Component {
  state = {
    number:0
  }
  handle = ()=>{
    this.setState({
      number:this.state.number + 1
    })
  }
  render() {
    return (
      <div>
        <Child num = {this.state.number}/>
        <button onClick={this.handle}>+1</button>
      </div>
    )
  }
}
// 子组件
function Child(props){
  return (
    <h3>这里是子组件:{props.num}</h3>
  )
}
ReactDOM.render(<Index/>,document.getElementById("root"))

2.子向父

// 父组件
export default class Index extends React.Component {
  state = {
    number:0,
    msg:""
  } 
  getval = msg =>{ 
    this.setState({
      msg
    })
  }
  render() {
    return (
      <div>
        <h5>{this.state.msg}</h5>
        <Child getMsg = {this.getval}/> 
      </div>
    )
  }
}
// 子组件
function Child(props){
  const  handle = ()=>{
     props.getMsg('子组件的传递的值')
  }
  return (
    <div>
      <h3>这里是子组件</h3>
      <button onClick={handle}>+1</button>
    </div>
  )
} 

3.兄弟组件传值

 export default class Index extends React.Component {
   constructor(props){
     super(props)
     this.state = {
       count:0
     }
   }
   handle = params =>{
     this.setState({
      count:this.state.count + params
     }) 
   }
   render() {
     return (
       <div>
          <Child1 count = {this.state.count}/>
          <Child2 getAdd = {this.handle}/>
       </div>
     )
   }
 }
 
  class Child1 extends React.Component { 
   render() { 
     return (
       <div>
          计数器:{this.props.count}
       </div>
     )
   }
 }
  
  class Child2 extends React.Component {
    handle = ()=>{
      this.props.getAdd(1)
    }
  render() {
    return (
      <div>
          <button onClick={this.handle}>+1</button>
      </div>
    )
  }
} 
ReactDOM.render(<Index/>,document.getElementById("root"))

03.规则校验

1.安装

npx add prop-types -save

2.引入

import propTypes from 'prop-types'

3.使用

// 规则校验  
import propTypes from "prop-types";
export default class Index extends React.Component {
  state = { 
    count:0
  }
  render() { 
    return (
      <div>
        <Child count = {this.state.count}/>
        <h1>{this.props.name}</h1>
      </div>
    )
  }
} 
class Child extends React.Component {
  render() {
    return (
      <div>
        <h1>这里是子组件:{this.props.count}</h1>
      </div>
    )
  }
}
// 必填项
Child.propTypes = {
  count:propTypes.number.isRequired
} 
// 默认值
Child.defaultProps = {
  count:100
}

04.生命周期

1.挂在阶段

export default class Index extends React.Component {
	constructor(props){
		super(props)
		console.log("constructor") // 第一步执行
	} 
	componentDidMount(){
		console.log('componentDidMount') // 第三步中兴
	}
	render(){
	   console.log('render') // 第二步执行
	   return (
	   	<div> 页面结构 </div>
	   )
	}
}

2.更新阶段

// 1.setState({})  2.New props  3.foceUpdata() 导致render渲染
export default calss Index extends React.Component {
	Freash = () =>{
		this.forceUpdata()
	}
	componentDidUpdata(){
		console.log('componentDidUpdata') // 第二步执行
	}
	render(){
	    console.log('render') // 1.第一步执行
		return (
			<div>
				<button 
				   onClick={this.Freash}
				  >
				  点击刷新   					                             </button>		
			</div>
		)
	}
}

3.卸载阶段

export default class delComponent extends React.Component {
	componentWillUnmount(){
		console.log('componentWillUnmount')
	}
	render(){
		return (
			<div> 组件的卸载 </div>
		)
	}
}

05.componentDidUpdate 中 setState 报错

classzezd Index extends React.Component { 
  componentDidUpdate(proProps){
    if( preProps.count !== this.props.count ){
           this.setState({
             count:this.props
           })
     }
     render() { 
        console.log("render02");
        return (
          <div>
             <h1>打豆豆:{this.props.count}</h1>
          </div>
        )
      }
	}
}

06.高阶组件

1.ender props 模式

// render props 模式
import img from "./img/111.jpeg";
import propTypes from "prop-types"; 
export default class Index extends React.Component {
  render() {
    return (
      <div>
        <Child>
          {
            data => <p>初始距离:(x:{ data.x },y:{ data.y })</p>
          }
        </Child>
        <Child>
          {
            data => {
              return (
                <img src={img} style={{ 
                  position:'absolute',
                  width:"100px",
                  height:"100px",
                  left:data.x- 50,
                  top:data.y- 50
                 }} alt="22" />
              )
            }
          }
        </Child>
      </div>
    )
  } 
}
class Child extends React.Component {
  state = {
    x:0,
    y:0
  }
  handle = e =>{ 
    this.setState({
      x:e.clientX,
      y:e.clientY
    })
  }
  componentDidMount(){
    window.addEventListener("mousemove",this.handle)
  }
  componentWillUnmount(){
    window.removeEventListener("mousemove",this.handle)
  }
  render() { 
    return this.props.children(this.state)
  }
}
Child.propTypes = {
 children: propTypes.func.isRequired
}

2.高阶组件(封装)

// 高阶组件
import img from "./img/111.jpeg"; 
function WithMouse(Withcomponent) { 
  class Child extends React.Component { 
    state = {
      x:'',
      y:''
    }
    handele = e => {
      this.setState({
        x:e.clientX,
        y:e.clientY
      })
    }
    componentDidMount(){
      window.addEventListener("mousemove",this.handele)
    }
    componentWillUnmount(){
      window.removeEventListener('mousemove',this.handele)
    }
    render() {
      return  <Withcomponent {...this.state} {...this.props}/>
    }
  } 
  Child.displayName = `With${getDiaplayName(Withcomponent)}`
  return Child
}
// 组件取名
function getDiaplayName(Withcomponent){ 
  return Withcomponent.displayName || Withcomponent.name || 'Component'
}
const Child1 = params => {  
  return <p>当前位置(x:{params.x},y:{params.y})</p> 
}
const Child2 = params => 
{
  return <img src={img} 
              alt="图片"
              style={{
                position:"absolute",
                width:'100px',
                height:'100px',
                left:params.x - 50,
                top:params.y - 50
              }}
              />
} 
let Com1 = WithMouse(Child1)
let Com2 = WithMouse(Child2) 
class Index extends React.Component { 
  render() {
    return (
     <div>
         <Com1 num={20}/>
         <Com2 />
     </div>
    )
  }
}

07.路由

import { BrowserRouter as Router,Route,Link } from "react-router-dom";
 
import { Login,Regdit } from "./pages/login/login.js";
export default class Index extends React.Component {
  render() {
    return (
     <Router>
      <div>
        <h1>这里哦是根组件</h1> 
          {/* 路由入口 */}
          <Link to="/">登录页</Link> | |  
          <Link to="/regdit">注册页</Link> 
          {/* <Link to="/login">注册</Link>  */}
          {/* 路由出口 */}
          <Route exact path="/" component={Login}/> 
          <Route  path="/regdit" component={Regdit}/> 
      </div>
      </Router>
    )
  }
} 

08.createContext() 传值

// 跨组件传值
const { Provider,Consumer } = React.createContext()

class Index extends React.Component {
  render() {
    return (
      <Provider value="pink">
      <div>
        <Child1 />
      </div>
      </Provider>
    )
  }
} 
class Child1 extends React.Component {
  render() {
    return (
      <div>
        <h1>这里是组件2</h1>
        <Child2/>
      </div>
    )
  }
}
class Child2 extends React.Component {
  render() {
    return ( 
      <div>
         <Consumer> 
          {
            data => <h1>{data}</h1>
          }
        </Consumer>
      </div> 
    )
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值