日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

04 组件与Props

發(fā)布時間:2023/12/10 编程问答 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 04 组件与Props 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一些概念

  • 組件:視圖的片段、內(nèi)部管理數(shù)據(jù)集合(state)外部傳入配置結(jié)合(props)
  • 包含: 1. 視圖標記(React的JSX、Vue的template)需要經(jīng)過轉(zhuǎn)換而成為真實的DOM
  • 事件
  • 數(shù)據(jù)
  • 邏輯(存儲storage、數(shù)據(jù)結(jié)構(gòu)化處理)
  • 外部的配置

屬性props和數(shù)據(jù)/狀態(tài)state的區(qū)別

  • state → 數(shù)據(jù)池 組件內(nèi)部的管理數(shù)據(jù)的容器 組件內(nèi)部可讀寫
  • props → 屬性池 外部調(diào)用組件時傳入的屬性集合 組件內(nèi)容只讀不可寫
  • 組件渲染過程

  • React主動調(diào)用Mytitle自定義組件
  • 將屬性集合轉(zhuǎn)換對象 props → { title: 'xxx'}
  • 將對象作為props傳入組件
  • 替換JSX中的props或者state中的變量
  • ReactDOM將最終的React元素通過一系列操作轉(zhuǎn)換成真實DOM進行渲染
  • 組件調(diào)用規(guī)范

  • 視圖標記:HTML標簽 <h1></h1>
  • 大駝峰寫法作為一個React元素 <Mytitle />組件 → JSX → React元素
  • 組件轉(zhuǎn)換React元素 React.createElement參考下面代碼
  • 使用props(類組件)

    class Mytitle extends React.Component {constructor(props) {super(props)}state = {title: this.props.title}changeTitle() {this.setState({title: 'new title'})}render() {return (<div><h1>{this.state.title}</h1><button onClick={this.changeTitle.bind(this)}>修改</button></div>)} } ReactDOM.render(<Mytitle title="init title" />,document.getElementById('app') )

    使用hooks(函數(shù)組件,不寫class了)

    • 函數(shù)組件一定要是一個純函數(shù)(入?yún)⒉豢尚薷?#xff0c;能保證絕對的復(fù)用性)
    • 注意onClick綁定的不是函數(shù)執(zhí)行setTitle('new title'),而應(yīng)該是一個匿名函數(shù)
    • 或者用bind返回一個函數(shù)
    function Mytitle(props) {const [title, setTitle] = React.useState(props.title)return (<div><h1>{title}</h1><button onClick={() => setTitle('new title')}>修改</button>// or// <button onClick={setTitle.bind(this, 'new title')}>修改</button></div>) } ReactDOM.render(<Mytitle title="init title" />,document.getElementById('app') ) // or不寫jsx // ReactDOM.render( // React.createElement(Mytitle, { // title: 'init title' // }), // document.getElementById('app') // )

    使用展開運算符

    // 省略 state = {title: 'title',author: 'author' } render(){return (<Title {...this.state }/>) } // 相當于 <Title title="this.state.title" author="this.state.author" />

    總結(jié)

    以上是生活随笔為你收集整理的04 组件与Props的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。