开发中遇到大屏小屏来回切换的问题。
所以会有字体大小自适应的需求

StoreFactory.tsx中

interface IContexxt {
    state:any,
    dispatch?:React.Dispatch<any> | undefined
}
export const createStore =(reducer:(state:any,action:any)=>object,defaultState:object,dispatchAction:any) =>{
    const Context = React.createContext<IContext>({state:defaultState});
    const useAction = () =>{
        const {dispatch} = useContext(Context);
        return dispatchAction(dispatch);
    }
}
return {useAction};

appStore.ts中

import {createStore} from './storeFactory';
import {appReducer,defaultState} from './reduce';
import {dispatchAction} from './action';
const {useAction,withStore,useStore}  = createStore(appReducer,defaultState,dispatchAction);

export {withStore,useStore as useAppStore,useAction as useAppAction};

App.tsx中

const UIWidth = 1920   // 设计稿宽度
const RootFontSizeRate = 100  // rem px换算比例 

const App: React.FC = () =>{
    const action = useAppAction();
    useEffect(()=>{
        setRootFontsize();
        window.onresize =() ={
            setRootFontSize()
    }
    return ()={
        widow.onresize = null;
    }

    },[])
}

const setRootFontSize = ()=>{
    const {clientWidth} = document.documentElement;
    const rootFontSize = clientWidth/UIWidth* RootFontSizeRate;
    document.documentElement.style.fontsize = `${rootFontSize}px`
    action.setRootFontSize(rootFontSize);
}

HeiYanjing
45 声望1 粉丝

生活本就很艰难,且行且珍惜。


下一篇 »
React只读列表