react 組件間參數傳遞


基礎用法、父子通信
①傳值
<MyHeader myTitle="這是登錄頁面">
</MyHeader>
②接收
在MyHeader組件中接收通過myTitle屬性給 傳遞的數據
this.props.myTitle
 var MyHeader = React.createClass({
       render:function(){
         return <h2>
          {this.props.myTitle}
         </h2>
       }
     })


     ReactDOM.render(
       <MyHeader  myTitle="這是標題內容"></MyHeader>,
       document.getElementById('example')
     )
父與子通信
在react中,可以通過自定義屬性傳一個普通的字符串,還可以傳一個方法

子與父通信的標准版流程:
①父定義一個有參數的方法
rcv:function(msg){}
②將此方法傳遞給子組件
<son func={this.rcv}></son>
③子組件來調用由參數方法,將數據傳遞到父組件
this.props.func(123)
 var MyButton = React.createClass({
      handleClick:function(){
        this.props.func(10)
      },
      render:function(){
        return <button 
        onClick={this.handleClick}>{this.props.btnText}</button>
      }
    })

    var MyCart = React.createClass({
      funcDel:function(index){
        alert('下標為'+index+'的商品刪除成功')
      },
      funcSubmit:function(){
        alert('結算成功')
      },
      render:function(){
        return <div>
         <MyButton btnText="刪除" func={this.funcDel}></MyButton>
         <MyButton btnText="結算" func={this.funcSubmit}></MyButton>
        </div>
      }
    })
    
    ReactDOM.render(
       <MyCart></MyCart>,
       document.getElementById('example')
     )
兄弟通信
ReactJS中 並沒有直接提供兄弟通信的解決方案:
借助於共同的父組件來完成兄弟通信過程

this.props.children
組件類this.props對象中的keyValue,和調用組件時所指定的屬性是一一對應的;其實有一個例外:this.props.children

可以通過this.props.children來獲取到組件在被調用時 內部的子元素

注意事項:
this.props.children類型是不確定的,如果一個字標簽都沒有:undefined
如果只有一個:object
如果有多個:array

React中實現一個方法來方便的遍歷this.props.children:

React.Children.map(
this.props.children,
(value)=>{
return value
}
)



免責聲明!

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



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