react组组件传值给父组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/koufulong/article/details/80228458

例子:

子组件


import React, { Component } from 'react'

export default class Item extends Component {
 constructor(props) {
  super(props)

  this.state = {
   page: 0
  }
 }

  //用传过来的changePage属性(props),是个函数,呼叫它把page交给父组件中的函数去处理
  this.props.changePage(page)


 render() {

    return (
     <div>
       {this.state.page}
     </div>
    )
 }
}

父组件

import React, { Component } from 'react';
import Item from './Item'

class App extends Component {
 constructor(props) {
  super(props)

  this.state = {price: 0}
 }

 //给子组件用来传price用的方法
 page(price){
  this.setState({page: page})
 }

 render() {
  return (
   <div>
    <Item page={this.page.bind(this)}/>
   </div>
  );
 }
}

猜你喜欢

转载自blog.csdn.net/koufulong/article/details/80228458