(HP)react日常开发技巧
高级特性
1,protals(传送门):将子组件渲染到父组件之外。
实例场景:父组件的儿子是<Modal>组件,使用fixed定位虽然样式看着是在父组件之外了,但是打开控制台查看元素,Modal相关的html还是嵌套在id='App'里面。由于fixed定位的元素最好是直接放到body里具有更好的兼容性,所以需要使用protals让modal渲染到body下:
import ReactDom from 'react-dom';class Test extends from React.component{render(){return ReactDom.createPortal(<div className="modal">这是一个模态框</div>, document.body)}
}
常用场景:
fixed浏览器兼容性,父组件z-index太小,父组件设置了overflow:hidden
2,context:多层级组件传值
场景:使用props层层传递太啰嗦,使用redux太繁重。
那么可以选择使用context或者recoil
// A.jsx
const ThemeContext = React.creatContext('light')class A extends React.Component{this.state ={ theme: ''}render(){<ThemeContext.Provider value={this.state.theme} ><B /><button onClick={()=>setState({val:'hh'})} ></button></ThemeContext.Provider>}
}// B.jsxclass B extends React.Component{render(){<div><C /></div>}
}// C.jsx(class组件)class C extends React.Component{const { theme }= this.context;static contextType = ThemeContext render(){<div>{theme}</div>}
}C.contextType=ThemeContext // 如果不这样写,需要在C组件中将注释打开// C.jsx (函数组件)
function C (){
return <ThemeContext.Consumer> {theme=>theme} </ThemeContext.Consumer>
}
性能优化
1,异步加载组件:
组件比较大import()或者路由懒加载React.Lazy,React.Suspense
import():正常的组件会随着整个项目打包成一个MD5.js的文件,但是异步加载的组件会单独打包成一个md5.js文件
React.Lazy():相当于一个构造函数,将引入的组件作为输入,封装后输出一个异步的组件
React.Suspense
const Dom = React.lazy(()=>import('../bigComponent')class App extends from React.component{render(){return <React.Suspense fullback={<div>...loading</div>}><Dom /></React.Suspense>}
}
2,scu
memo(配合useMemo,useCallback使用)
比如以下结构代码:
// index.tsx
const Index=()=>{
const [val,setVal]=useState(1);
const [b,setb]=useState('hh');
const add = ()=>setVal(val+1);
const callbackFn = ()=>alert('hi');
return <div><button onClick={add}>按钮{val}</button><B b={b} callbackFn={handle} />
</div>
}// B.tsx
const B = (b,callbackFn)=>{
console.log('我又被执行了一遍,这就是刷新了这个组件')
return <div>{b}
</div>
}
每次点击按钮B组件都会打印那句话,这就说明B组件的代码又被执行了一遍进行重复渲染。为了解决这个重复渲染,变量用useMemo封装起来,函数用useCallback封装起来
// index.tsx
const Index=()=>{
const [val,setVal]=useState(1);
const [b,setb]=useState('hh');
const add = ()=>setVal(val+1);const bprops = useMemo(()=>b,[b]);
const callbackFn = useCallback(()=>alert('hi'),[]);return <div><button onClick={add}>按钮{val}</button><B b={b} callbackFn={handle} />
</div>
}// B.tsx
const B = (b,callbackFn)=>{
console.log('我又被执行了一遍,这就是刷新了这个组件')
return <div>{b}
</div>
}