提高React組件的復用性


1. 使用props屬性和組合

1. props.children

在需要自定義內容的地方渲染props.children

function Dialog(props) { //通用組件
  return (
    <div>
      <h1 className="dialog-title">{props.title}</h1>
      <p className="dialog-message">
        {props.message}
      </p>
      {
        props.children //在組件最后用戶可以自定義添加內容
      }
    </div>
  )
}
class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      loginName: ''
    }
  }
  handleChange = (e) => {
    this.setState({
      loginName: e.target.value
    })
  }
  render() {
    return (
      <Dialog 
        title="welcom" 
        message="Thank you for visiting our spacecraft!"
      >
        <input 
          type="text" 
          value={this.state.loginName} 
          onChange={this.handleChange}
        />
        <button>
          注冊
        </button>
      </Dialog>
    )
  }
}

2. 將組件作為變量傳遞到另一個組件

function Dialog(props) { //通用組件
  return (
    <div>
      {
        props.selfDefine ||  <h1 className="dialog-title">{props.title}</h1>
      }
      <p className="dialog-message">
        {props.message}
      </p>
    </div>
  )
}
class SignUpDialog extends React.Component {
  render() {
    const h2 = <h2>這是自定義的標題</h2>;
    return (
      <Dialog 
        title="welcom" 
        message="Thank you for visiting our spacecraft!"
        selfDefine={h2}
      />
    )
  }
}

 2. 高階組件

詳情

3. Render props

統指屬性值是函數的屬性,返回值用於指定渲染內容。

當將函數作為屬性時,如果函數直接定義在屬性上,每次render都會生成一個新的函數;會導致props始終處於變化狀態。這時和PureComponent沖突。
解決辦法:
1)將PureComponent改為Component
2) 函數傳入函數實例。在外部定義好函數后傳入

屬性名稱可以隨意指定,children也可以是一個返回渲染內容的函數。

這個屬性很多時候可以替代高階組件;也可以和高階組件一起使用。

import img from './cat.png';
import './index.css';

class Cat extends React.Component {
  render() {
    const { x, y} = this.props.mouse;
    return (
      <img style={{position: 'absolute', top:y, left: x }} src={img} />
    )
  }
}

// 公用組件;相當於高階組件的公共部分
class Mouse extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      x: 50,
      y: 0
    }
  }
  handleMouseOver = (e) => {
    this.setState({
      x: e.clientX,
      y: e.clientY
    })
  }
  render() {
    return (
      <div style={{height: '100%'}} onMouseMove={this.handleMouseOver}>
        <h1>查看鼠標</h1>
        {this.props.renderMouse(this.state)}
      </div>      
    )
  }
}
class MouseTracker extends React.Component {
  render() {
    return(
      <Mouse renderMouse={(mouse) => <Cat mouse={mouse}/>}/>
    )
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM