react18初学者实用方法

从VUE3突然使用React,虽然知道要做什么,但却不知道怎么使用React编写,现在已经很熟练的使用了,总结几个比较实用的给初学者;放心学习没副作用;

鼠标双击
<div onDoubleClick={}></div>
input搜索代码高亮
<div dangerouslySetInnerHTML={{
__html: item.name.replace(searchText.current,
    '<span style=\'color: #58AEFF;\'>'+searchText.current+'</span>')}}>
</div>
input默认值,修改不成功后返回默认值
interface PropsType {
    curGroupName: string, // 当前群组名称
}
export default function ReviseGroupName(props:PropsType) {
    // 绑定input
    const TemplateNameInput = useRef<HTMLInputElement>(null);
    useEffect(() => {
        methods.initInputValueToProps();
        return () => {};
    }, [props.curGroupName])
    const methods = { // 定义当前页面所有方法
        handleInputBlur() { // 处理input失去焦点
            const currentVal = TemplateNameInput.current?.value || '';
            if (currentVal) {
                if (currentVal === props.curGroupName) { return; };
                // 修改中发送ajax
                
            } else { // 修改失败返回传入默认值;
                methods.initInputValueToProps();
            };
        },
        initInputValueToProps() { // 恢复props传入默认值
            if (TemplateNameInput.current) {
                TemplateNameInput.current.value = props.curGroupName || '';
            }
        }
    }
    return (
        <input type='text' placeholder='请输入' maxLength={20} 
        onBlur={methods.handleInputBlur}
        ref={TemplateNameInput} />
    )
}
按钮disabled
handleClick(event){
    event.currentTarget.disabled = true;
}
<button onClick={handleClick}></button>
Promise定义类型
getUserList(){
    interface userList{
        name: string, age: number,
    }
    return new Promise<userList>((resolve, reject) => {
    })
}
定时器加Map更新
// 第一种玩法
let timerId: string | number | NodeJS.Timeout | null | undefined = null;
const [meetingTimingMap, setMeetingTimingMap] = useState<Map<string, string>>(new Map());
const [list, setList] = userState([])
useEffect(() => {
    methods.handleMettingTimeTimer();
    return () => { // 销毁
        timerId && clearTimeout(timerId);
    };
    /* 我当时做的是给列表中的数据加倒计时,所以我必须监听这个列表;
        不然的话methods.handleMettingTimeTimer(),中获取的list可能会是初始值;
    */
}, [list]); 
const methods = {
    handleMettingTimeTimer() {
         timerId && clearTimeout(timerId);
         meetingTimingMap.clear();
         /*
             ...处理逻辑
         */
         // 更新map
         setMeetingTimingMap(new Map([...meetingTimingMap.entries()]));
         setTimeout(() => {methods.handleMettingtimeTimer()}, 1000)
    }
}
// 第二种的玩法就是把定时器写在useEffect中
useEffect(() => {
    let timerId: string | number | NodeJS.Timeout | null | undefined = null; 
    let runTime = () => {
        timerId && clearTimeout(timeId);
        // 处理逻辑
        timerId = setTimeout(runTime, 1000);
    }
    timerId = setTimeout(runTime, 1000);
    return () => { // 销毁
        timerId && clearTimeout(timerId);
    };
}, [])
父调用子方法
// 父组件
import {createRef} from 'react';
export default Parent() {
    const childRef: any = createRef();
    // childRef.current.refreshList(); // 使用
    return (
        <>
            <Child ref={childRef}></Child>
        </>
    )
}
// 子组件
import {useImperativeHandle, forwardRef } from 'react';

const Child = forwardRef((props, ref)=> {
    useImperativeHandle(ref,
        () => ({
            'refreshList': (item: any) => {
            }
        })
    );
})
export default Child;
默认props
import React, { PropsWithChildren } from 'react';
type ChildProps{
    title: string;
}
Child.defaultProps{
    title: 'yyh';
}
export default Child({title}: PropsWithChildren<ChildProps>) {
}
useState 默认值
const [count, setCount] = useState<number>(0)
const [list, setList] = useState<number[]>(0)
props回调函数
type ChildProps{
     myCallback: () => void;
}
export default Child({myCallback}: ChildProps) {
    <div onClick={myCallback}></div>
}
阻止冒泡
export default Child() {
    <div onClick={}>
        <div onClick={(el) => {
            el.stopPropagation();
        }}></div>
    </div>
}
Child插槽类型
// 子组件
import React from 'react'
type CardProps = { children: React.ReactNode; };
export function CardSlot({children }: CardProps) {
  return (
    <section >
      {children}
    </section>
  );
}
// 父组件
<CardSlot>
    <div>...</div>
</CardSlot>
动态绑定多个props
// React子组件可以使用`{...props}`来动态绑定多个props。这个语法叫做"属性扩展"或者"对象展开"。
function ParentComponent() {
    const props = { prop1: 'value1', prop2: 'value2', prop3: 'value3' }; 
    return <ChildComponent {...props} />; 
}
function ChildComponent(props){
    return (
        <>
            <div>{props.prop1}{props.prop2}{props.prop3}</div>
        </>
    )
}
  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值