前言
在最近做的一個react項目中,遇到了一個比較典型的需要重構的場景:提取兩個組件中共同的部分。
最開始通過使用嵌套組件和繼承的方式完成了這次重構。
但是后來又用高階組件重新寫了一遍,發現更好一點。
在這里記錄下這兩種方式以便之后參考和演進。
本次重構的場景
因為場景涉及到具體的業務,所以我現在將它簡化為一個簡單的場景。
現在有兩個黑色箱子,箱子上都有一個紅色按鈕,A箱子充滿氣體,按了按鈕之后箱子里面氣體變紅,B箱子充滿泥土,按了之后箱子里面泥土變紅。
那么現在上一個簡單的重構前代碼:
BoxA.jsx
import React, { Component, PropTypes } from 'react'class BoxA extends Component { state={ color:'black' } handleClick=()=>{ this.setState({ color:'red' }) } handleShake=()=>{ /* 搖動后氣體沒聲音 */ } render() { return ( /* 這里面當然沒有onShake這種事件,理解意思就行了 */ <div style={{backgroundColor:'black'}} onShake={this.handleShake}> <button onClick={this.handleClick} style={{backgroundColor:'red'}}></button> <div> /* 氣體組件,沒毛病 */ <氣體 color={this.state.color} /> </div> </div> ) }}BoxB.jsx
import React, { Component, PropTypes } from 'react'class BoxB extends Component { state={ color:'black' } handleClick=()=>{ this.setState({ color:'red' }) } handleShake=()=>{ /* 搖動后泥土有聲音 */ } render() { return ( <div style={{backgroundColor:'black'}} onShake={this.handleShake}> <button onClick={this.handleClick} style={{backgroundColor:'red'}}></button> <div> <泥土 color={this.state.color} /> </div> </div> ) }}使用嵌套組件進行重構
看看上面的代碼,即使在業務簡化的情況下都有很多重復的,所以得重構。
對于這種很明顯的箱子類問題,一般都會采用嵌套組件的方式重構。
Box.jsx
import React, { Component, PropTypes } from 'react'class Box extends Component { static propTypes = { children: PropTypes.node, onClick: PropTypes.func, onShake: PropTypes.func } render() { return ( <div style={{backgroundColor:'black'}} onShake={this.props.onShake}> <button onClick={this.props.onClick} style={{backgroundColor:'red'}}></button> <div> {this.children} </div> </div> ) }}BoxA.jsx
import React, { Component, PropTypes } from 'react'import Box from './Box.jsx'class BoxA extends Component { state={ color:'black' } handleClick=()=>{ this.setState({ color:'red' }) } handleShake=()=>{ /* 搖動后氣體沒聲音 */ } render() { return ( <Box onClick={this.handleClick} onShake={this.props.handleShake}> <氣體 color={this.state.color} /> </Box> ) }}
新聞熱點
疑難解答
圖片精選