1. 程式人生 > 實用技巧 >react子傳父

react子傳父

react裡子元件不能直接操作父元件的資料。

所以要從父元件傳遞一個方法給子元件,

子元件獲取到該方法後,把子資料傳入該方法,

父元件才能獲取到子資料

例子:

子元件 Child.js

import React, { Component } from 'react'
class Child extends Component{
    constructor(props){
        super(props)
        this.state = {
            cdata:"子元件資料"
        }
    }
    render(){
        return
( <div> <button onClick={this.trans.bind(this,this.state.cdata)}>確定</button> </div> ) } //點選子元件時,定義一個方法,呼叫父元件傳過來的方法,把子元件資料傳入到這個方法裡 trans(data){ this.props.content(data) } } export default Child;

父元件App.js

import React, { Component } from 'react';
import Child from 
'./Child' class App extends Component{ constructor(props){ super(props) this.state = { pdata:"父元件資料" } } render(){ return( <div> {/* 傳遞一個方法給子元件 */} <Child content={this.getValue.bind(this)}></Child> {this.state.pdata} </div> ) }
//在方法裡傳入一個引數,val就是子元件傳過來的資料 getValue(val){ this.setState({ pdata:val }) } } export default App;

使用箭頭函式的寫法

子元件:

import React, { Component } from 'react';
class Child extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            cdata:"子資料"
         }
    }
    render() { 
        return ( 
            <div>
                子元件
                <button onClick={()=>this.transValue(this.state.cdata)}>傳遞資料</button>
            </div>
         );
    }
    transValue(val){
        console.log(val);
        
        this.props.content(val)
    }
}
 
export default Child;

父元件

import React, { Component } from 'react';
import Child from './Child'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
        pdata:"父資料"
      }
  }
  render() { 
    return ( 
      <div>
        {this.state.pdata}
        {/* 這個方法要傳入引數 */}
        <Child content={(val)=>this.giveMeth(val)}></Child>
      </div>
     );
  }
  giveMeth(val){
    console.log(val);
    
  }
}
 
export default App;