react知识点整理

本文介绍了React中函数组件和类组件的定义、传参方式以及生命周期函数的使用。讨论了如何使用useState和useRef进行状态管理和DOM引用,利用useEffect进行数据监听。同时,提到了Redux在状态管理中的应用,高阶组件的概念以及路由跳转的方法。此外,还涵盖了国际化实现和Helmet设置浏览器标题的功能。
摘要由CSDN通过智能技术生成

函数组件

1、定义

const loginView = () =>{

}
export default loginView

2、传参

//父组件
const about = () => {
    const getChild = (e)=>{
        console.log(e)
    }
    return (
        <Comp2 name={'xiaoy'} getChild={getChild}/>
    )
}
export default about

//子组件
import React from "react";
const Comp2 = (props) =>{
    const get = ()=>{
        props.getChild("green")
    }
    return (
        <div className={'red'}>
            <div>这是父组件传过来的值{props.name}</div>
            <button onClick={get}>传值给父组件</button>
        </div>
    )
}
export default Comp2

类组件

1、定义

class Comp1 extends Component<any, any> {

}
export default Comp1

2、传参

//父组件
const about = () => {
    const getMsg = (e) => {
        console.log('about组件接收到了子组件的值:'+e)
    }
    return (
        <Comp1 name={'xiaoy'}  getMsg={getMsg}/>
    )
}
export default about

//子组件
class Comp1 extends Component<any, any> {
    sendMsg = ()=> {
        this.props.getMsg('Comp1')
    }
    render(){
        {this.props.name}
        <Button type="primary" onClick={this.sendMsg}>传值给父组件</Button>
    }
}

3、生命周期函数

class Comp1 extends Component<any, any> {
    //constructor 不算生命周期函数
    constructor(props) {
        //只有使用super,才能在构造函数中使用this关键字
        super(props);
        console.log(this.props)
    }

    //react17之后已废弃,组件挂载前调用
    componentWillMount(){
        console.log('componentWillMount')
    }
    //组件挂载后调用
    componentDidMount() {
        console.log('componentDidMount')
    }

    //控制组件更新,返回false,点击编辑数据一直不更新
    shouldComponentUpdate(nextProps: Readonly<any>, nextState: Readonly<any>, nextContext: any): boolean {
        console.log('shouldComponentUpdate')
        return true
    }
    //react17之后已废弃,组件更新前调用
    componentWillUpdate(){
        console.log('componentWillUpdate')
    }
    //组件更新后调用
    componentDidUpdate(){
        console.log('componentDidUpdate')
    }
    //react17之后已废弃
    componentWillReceiveProps() {
        console.log('componentWillReceiveProps ---------')
    }
    //组件卸载前调用
    componentWillUnmount(){
        console.log('componentWillUnmount')
    }
}

函数组件与类组件的区别

(1)类组件需要继承Component,函数组件不需要

(2)类组件中可以使用生命周期函数,函数组件不可以

(3)类组件中可以使用this关键字,函数组件不可以

尽量使用函数组件,因为类组件需要实例化

组件传参还可以是代码

//组件1
return (
    <Role content={
        <div>
            <span>666</span>
            <span>888</span>
        </div>
    }>
    </Role>
)

//组件2
const role = (props) => {
    return (
        <div className='home'>
            <p>这是Role组件开始</p>
            插槽内容{props.content}
            <p>这是Role组件结束</p>
        </div>
    )
}
export default role

运行结果

使用state更新渲染数据

const user = () => {

    const [inputValue, setInputValue] = useState()

    const get = (e: ChangeEvent<HTMLInputElement>) => {
        setInputValue(e.target.value)
    }

    return (
        <input value={inputValue} ref={inputRef} onChange={get}/>
        {inputValue}
    )
}
export default user;

 useRef

const inputRef = useRef<HTMLInputElement>()

const get = () => {
    console.log(inputRef.current.value)
}

render(
    <input value={inputValue} ref={inputRef} onChange={get}/>{inputValue}
)

useEffect监听数据

useEffect(() => {
    fetchData();
    //第二个参数,不传一直执行;第二个参数传空数组[],只运行一次(组件挂载和卸载时执行);第二个参      数传值,当依赖的数据源发生改变时,执行;相当于vue中的watch
}, [inputValue]);

useMemo计算

//用于计算
const res = useMemo(() => {
   return counts + 3
}, [counts])

redux

//通过useSelector获取仓库数据
const {num} = useSelector((state: numState) => ({
    num: state.numState.num
}))

//通过useDispatch修改仓库数据
const dispatch = useDispatch()
const changeNum = () => {
    dispatch({type: 'add'})
}

高阶组件,函数传入一个组件,返回一个新的组件

// 定义一个高阶组件
import {PureComponent} from "react";
function Hoc(Cpn) {
    class NewCpn extends PureComponent {
        render() {
            return (
                <div>
                    <h1>888</h1>
                    <Cpn/>
                </div>
            )
        }
    }
    // 2.并且返回一个新的组件
    return NewCpn
}
export default Hoc


// 创建一个组件作为参数
import {PureComponent} from "react";
class Cpn extends PureComponent {
    render() {
        return (
            <div>
                <h2>Hello World</h2>
                <h1>6666</h1>
            </div>
        )
    }
}
export default Cpn


//在其他组件中使用
import Hoc from '@/components/hoc/hoc'
import Cpn from '@/components/hoc/Cpn'
// 调用高阶组件会返回一个新的组件
const HelloWorldHOC = Hoc(Cpn)
const role = (props) => {
    return (
        <div className='home'>
            <p>这是Role组件开始</p>
            <HelloWorldHOC/>
            <p>这是Role组件结束</p>
        </div>
    )
}
export default role

运行结果

路由

//路由跳转
import {useNavigate,useLocation} from "react-router-dom";
const navigateTo = useNavigate()
const menuClick = ()=>{
    navigateTo('/user')
}
//获取当前路由
const currentRoute = useLocation()
console.log(currentRoute.pathname)

useIntl国际化

//main.tsx
import {IntlProvider} from "react-intl";
import zh_CN from "@/locale/cn";
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
    /*删除React.StrictMode,否则路由会执行两遍*/
    <IntlProvider locale='zh' messages={zh_CN}>
        <Provider store={store}>
            <BrowserRouter>
                <App />
            </BrowserRouter>
        </Provider>
    </IntlProvider>
)

//新建cn.ts
const zh_CN = {
    start: '开始',
    switch: '切换'
}
export default zh_CN

//新建en.ts
const en_US = {
    start: 'start',
    switch: 'switch'
}
export default en_US

//组件中使用方法1
import {useIntl} from "react-intl";
const user = () => {
    const intl = useIntl();
    const t = (id) => intl.formatMessage({ id })  // 写成传参方式
    console.log('国际化start:'+t('start'))
}

//组件中使用方法2
return (
    <div className='home'>
        <FormattedMessage
            id="start"
            defaultMessage="开始"
         />
    </div>
)

Helmet设置浏览器头部标题

import { Helmet } from 'react-helmet';
return (
    <div className='home'>
        <Helmet>
            <title>关于</title>
        </Helmet>
    </div>
)

运行结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值