美文网首页
react子组组件传值给父组件

react子组组件传值给父组件

作者: Volon | 来源:发表于2019-06-20 17:47 被阅读0次

例子:

子组件


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>
  );
 }
}

相关文章

网友评论

      本文标题:react子组组件传值给父组件

      本文链接:https://www.haomeiwen.com/subject/zegjqctx.html