react 动态添加class_02.react进阶指南
react 進(jìn)階
懶加載
React.lazy函數(shù)能讓你像渲染常規(guī)組件一樣處理動態(tài)引入(的組件)。 Suspense加載指示器為組件做優(yōu)雅降級。 fallback屬性接受任何在組件加載過程中你想展示的 React 元素。
const OtherComponent = React.lazy(() => import('./OtherComponent'));function MyComponent() {return (<div><Suspense fallback={<div>Loading...</div>}><OtherComponent /></Suspense></div>); }Context
Context提供了一個(gè)無需為每層組件手動添加 props,就能在組件樹間進(jìn)行數(shù)據(jù)傳遞的方法,設(shè)計(jì)目的是為了共享那些對于一個(gè)組件樹而言是“全局”的數(shù)據(jù)。
// Context 可以讓我們無須明確地傳遍每一個(gè)組件,就能將值深入傳遞進(jìn)組件樹。 // 為當(dāng)前的 theme 創(chuàng)建一個(gè) context(“l(fā)ight”為默認(rèn)值)。 const ThemeContext = React.createContext('light');class App extends React.Component {render() {// 使用一個(gè) Provider 來將當(dāng)前的 theme 傳遞給以下的組件樹。// 無論多深,任何組件都能讀取這個(gè)值。// 在這個(gè)例子中,我們將 “dark” 作為當(dāng)前的值傳遞下去。return (<ThemeContext.Provider value="dark"><Toolbar /></ThemeContext.Provider>);} }// 中間的組件再也不必指明往下傳遞 theme 了。 function Toolbar(props) {return (<div><ThemedButton /></div>); }class ThemedButton extends React.Component {// 指定 contextType 讀取當(dāng)前的 theme context。// React 會往上找到最近的 theme Provider,然后使用它的值。// 在這個(gè)例子中,當(dāng)前的 theme 值為 “dark”。static contextType = ThemeContext;render() {return <Button theme={this.context} />;} }請謹(jǐn)慎使用,因?yàn)檫@會使得組件的復(fù)用性變差。
API:
React.createContext: 創(chuàng)建一個(gè) Context 對象。當(dāng) React 渲染一個(gè)訂閱了這個(gè) Context 對象的組件,這個(gè)組件會從組件樹中離自身最近的那個(gè)匹配的 Provider 中讀取到當(dāng)前的 context 值。只有當(dāng)組件所處的樹中沒有匹配到 Provider 時(shí),其 defaultValue 參數(shù)才會生效。
Context.Provider: 每個(gè) Context 對象都會返回一個(gè) Provider React 組件,它允許消費(fèi)組件訂閱 context 的變化。當(dāng) Provider 的 value 值發(fā)生變化時(shí),它內(nèi)部的所有消費(fèi)組件都會重新渲染。
Class.contextType: 掛載在 class 上的 contextType 屬性會被重賦值為一個(gè)由 React.createContext() 創(chuàng)建的 Context 對象。這能讓你使用 this.context 來消費(fèi)最近 Context 上的那個(gè)值。你可以在任何生命周期中訪問到它,包括 render 函數(shù)中。
Context.Consumer: 這里,React 組件也可以訂閱到 context 變更。這能讓你在函數(shù)式組件中完成訂閱 context。
Refs
Refs 提供了一種方式,允許我們訪問 DOM 節(jié)點(diǎn)或在 render 方法中創(chuàng)建的 React 元素。不能在函數(shù)組件上使用 ref 屬性,因?yàn)樗麄儧]有實(shí)例,可以在函數(shù)組件內(nèi)部使用 ref 屬性。
適合使用 refs 的情況: - 管理焦點(diǎn),文本選擇或媒體播放。 - 觸發(fā)強(qiáng)制動畫。 - 集成第三方 DOM 庫。
使用方法:
- Refs 是使用 React.createRef() 創(chuàng)建的,并通過 ref 屬性附加到 React 元素。 class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; } }
- 在 ref 的 current 屬性中被訪問 const node = this.myRef.current;
Refs 轉(zhuǎn)發(fā)
Ref 轉(zhuǎn)發(fā)是一項(xiàng)將 ref 自動地通過組件傳遞到其一子組件的技巧。子組件使用React.forwardRef接收ref。可用于Hoc處理ref。
const FancyButton = React.forwardRef((props, ref) => (<button ref={ref} className="FancyButton">{props.children}</button> ));// 你可以直接獲取 DOM button 的 ref: const ref = React.createRef(); <FancyButton ref={ref}>Click me!</FancyButton>;上例中,FancyButton 使用 React.forwardRef 來獲取傳遞給它的 ref,然后轉(zhuǎn)發(fā)到它渲染的 DOM button。這樣,使用 FancyButton 的組件可以獲取底層 DOM 節(jié)點(diǎn) button 的 ref ,并在必要時(shí)訪問,就像其直接使用 DOM button 一樣。
Fragments
Fragments 允許你將子列表分組,而無需向 DOM 添加額外節(jié)點(diǎn)。key 是唯一可以傳遞給 Fragment 的屬性
render() {return (<React.Fragment><ChildA /><ChildB /><ChildC /></React.Fragment>); }<React.Fragment></React.Fragment>可簡寫為<></>
高階組件(HOC)
HOC是參數(shù)為組件,返回值為新組件的函數(shù)。
HOC 不會修改傳入的組件,也不會使用繼承來復(fù)制其行為。相反,HOC 通過將組件包裝在容器組件中來組成新組件。HOC 是純函數(shù),沒有副作用。
示例:
// 此函數(shù)接收一個(gè)組件... function withSubscription(WrappedComponent, selectData) {// ...并返回另一個(gè)組件...return class extends React.Component {constructor(props) {super(props);this.handleChange = this.handleChange.bind(this);this.state = {data: selectData(DataSource, props)};}componentDidMount() {// ...負(fù)責(zé)訂閱相關(guān)的操作...DataSource.addChangeListener(this.handleChange);}componentWillUnmount() {DataSource.removeChangeListener(this.handleChange);}handleChange() {this.setState({data: selectData(DataSource, this.props)});}render() {// ... 并使用新數(shù)據(jù)渲染被包裝的組件!// 請注意,我們可能還會傳遞其他屬性return <WrappedComponent data={this.state.data} {...this.props} />;}}; }上例中class組件為HOC的容器組件,容器組件擔(dān)任分離將高層和低層關(guān)注的責(zé)任,由容器管理訂閱和狀態(tài),并將 prop 傳遞給處理渲染 UI。HOC 使用容器作為其實(shí)現(xiàn)的一部分,你可以將 HOC 視為參數(shù)化容器組件。
注意事項(xiàng):
- 不要在 render 方法中使用 HOC。
在render中使用會導(dǎo)致diff 算法在對比組件變化時(shí)每次檢測都不一樣,每次渲染都會進(jìn)行卸載,和重新掛載的操作,這不僅僅是性能問題 - 重新掛載組件會導(dǎo)致該組件及其所有子組件的狀態(tài)丟失。
- 務(wù)必復(fù)制靜態(tài)方法到容器組件上。
可以使用hoist-non-react-statics自動拷貝所有非 React 靜態(tài)方法 import hoistNonReactStatic from 'hoist-non-react-statics'; function enhance(WrappedComponent) { class Enhance extends React.Component {/*...*/} hoistNonReactStatic(Enhance, WrappedComponent); return Enhance; }
- Refs 不會被傳遞。
可用過Refs 轉(zhuǎn)發(fā)解決
常見的HOC:
redux的 connect
React.PureComponent
大部分情況下,你可以使用 React.PureComponent 來代替手寫 shouldComponentUpdate。只有當(dāng)檢測數(shù)據(jù)是數(shù)組或?qū)ο髸r(shí),由于淺拷貝的問題會導(dǎo)致比較出現(xiàn)偏差不能使用,此時(shí)使用深拷貝仍可繼續(xù)使用。
如以下代碼:
class CounterButton extends React.Component {constructor(props) {super(props);this.state = {count: 1};}shouldComponentUpdate(nextProps, nextState) {if (this.props.color !== nextProps.color) {return true;}if (this.state.count !== nextState.count) {return true;}return false;}render() {return (<buttoncolor={this.props.color}onClick={() => this.setState(state => ({count: state.count + 1}))}>Count: {this.state.count}</button>);} }可替換為:
class CounterButton extends React.PureComponent {constructor(props) {super(props);this.state = {count: 1};}render() {return (<buttoncolor={this.props.color}onClick={() => this.setState(state => ({count: state.count + 1}))}>Count: {this.state.count}</button>);} }Portals
Portal 提供了一種將子節(jié)點(diǎn)渲染到存在于父組件以外的 DOM 節(jié)點(diǎn)的優(yōu)秀的方案。
一個(gè) portal 的典型用例是當(dāng)父組件有 overflow: hidden 或 z-index 樣式時(shí),但你需要子組件能夠在視覺上“跳出”其容器。例如,對話框、懸浮卡以及提示框:
render() {// React 并*沒有*創(chuàng)建一個(gè)新的 div。它只是把子元素渲染到 `domNode` 中。// `domNode` 是一個(gè)可以在任何位置的有效 DOM 節(jié)點(diǎn)。return ReactDOM.createPortal(this.props.children,domNode); }React.StrictMode
StrictMode 不會渲染任何可見的 UI。它為其后代元素觸發(fā)額外的檢查和警告。嚴(yán)格模式檢查僅在開發(fā)模式下運(yùn)行;它們不會影響生產(chǎn)構(gòu)建。
作用:
- 識別不安全的生命周期
- 關(guān)于使用過時(shí)字符串 ref API 的警告
- 關(guān)于使用廢棄的 findDOMNode 方法的警告
- 檢測意外的副作用
- 檢測過時(shí)的 context API
React.memo
React.memo 為高階組件。它與 React.PureComponent 非常相似,但它適用于函數(shù)組件,但不適用于 class 組件。
如果你的函數(shù)組件在給定相同 props 的情況下渲染相同的結(jié)果,那么你可以通過將其包裝在 React.memo 中調(diào)用,以此通過記憶組件渲染結(jié)果的方式來提高組件的性能表現(xiàn)。這意味著在這種情況下,React 將跳過渲染組件的操作并直接復(fù)用最近一次渲染的結(jié)果。
默認(rèn)情況下其只會對復(fù)雜對象做淺層對比,如果你想要控制對比過程,那么請將自定義的比較函數(shù)通過第二個(gè)參數(shù)傳入來實(shí)現(xiàn)。
const MyComponent = React.memo(function MyComponent(props) {/* 使用 props 渲染 */ });原文git地址 覺得有用的話,來個(gè)star鼓勵,持續(xù)更新中。
原文地址 - 點(diǎn)擊獲取更多知識?github.com 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的react 动态添加class_02.react进阶指南的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql数据库备份提示1577_mys
- 下一篇: java bat 启动脚本_解析Tomc