React(7) --react父子組件傳參

react父子組件傳參react

父級向子級傳參:在父組件中,咱們引入子組件,經過給子組件添加屬性,來起到傳參的做用,子組件能夠經過props獲取父組件傳過來的參數。函數

在父組件中:this

import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
 render() {
   return (
     <div>
        <h1>父組件</h1>
        <ChildCom content={'我是父級過來的內容'}/>
     </div>
   )
 }
}
export default ParentCom;

在子組件中:spa

import React from 'react'
class ChildCom extends React.Component {
   render() {
     return (
       <div>
         <h2>子組件</h2>
         <div>
           {this.props.content}
         </div>
       </div>
    )
} } export
default ChildCom;

子級向父級傳參:在父組件中給子組件添加一個屬性,這個屬性的內容爲一個函數,而後在子組件中調用這個函數,便可達到傳遞參數的效果code

在子組件中:blog

import React from 'react'
class ChildCom extends React.Component {
   valueToParent(value) {
     this.props.onValue(value);
   }
   render() {
      return (
         <div>
            <h2>子組件</h2>
           <div>
             <a onClick={this.valueToParent.bind(this,123)}>向父組件傳值567</a>
           </div>
        </div>
   )
  }
}
export default ChildCom;

在父組件中:get

import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
   state = {
     getChildValue: ''
   }
   getChildValue(value) {
     this.setState({
        getChildValue: value
     })
   }
   render() {
      return (
        <div>
           <h1>父組件</h1>
           <div>子組件過來的值爲:{this.state.getChildValue}</div>
           <ChildCom onValue={this.getChildValue.bind(this)}/>
       </div>
     )
  }
}
export default ParentCom;
相關文章
相關標籤/搜索