iT邦幫忙

1

React 父組件傳遞 methods props 給子組件

挑戰 React 第十七篇

React 第十一篇了解透過 element 傳遞 props,此篇要介紹要寫傳父組件裡的方法給子組件

目標

  1. 子組件按了按鈕,印出父組件傳來的方法
  2. 子組件傳參數給父組件

實作步驟

  1. 新增一個 parent.js 檔案
  2. 在 parent.js 寫一個按鈕,按了會印出 Hello Parent
import React, { Component } from 'react'
import Child from './Child';

 class Parent extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       parentName: "parent"
    }
    // 需綁定 this,否則會找不到 hello method
    this.hello = this.hello.bind(this);
  }
  
  hello() {
    console.log(`Hello ${this.state.parentName}`);
  }

  render() {
    return (
      <div>
         <button onClick={this.hello}>button</button>
      </div>
    )
  }
}

export default Parent
  1. 試著 yarn start 前兩步驟

確認按了按鈕,有印出 Hello Parent

  1. 把 hello method 傳遞給子組件使用的寫法
render() {
    return (
      <div>
         // 把方法當作 element 傳遞下去給 Child 組件
         <Child hello = {this.hello}/>
      </div>
    )
  }
  1. 新增一個 child.js 檔案
import React, { Component } from 'react'

class Child extends Component {
  render() {
    return (
      <div>
        // 收到來自 parent 的 props,使用 hello method
        <button onClick={this.props.hello}>button</button>
      </div>
    )
  }
}

export default Child
  1. yarn start 前五步驟

確認按了按鈕,印出 Hello Parent
因此現在我們會用傳遞的方式拿到父組件的方法。

  1. 在子組件傳參數給父組件

Parent.js 父組件

 hello(childName) {
    console.log(`Hello ${this.state.parentName} from ${childName}`);
  }

Child.js 子組件

 render() {
    return (
      <div>
        // 傳入參數 Child
        <button onClick={() => this.props.hello('child')}>button</button>
      </div>
    )
  }
  1. yarn start 第七步驟

確認取得子組件傳來的參數,並印出 Child

小結論

當初學會這個方式的時候,覺得很方便,在我們組內有時候也會透過這個寫法達到某些目的,用 method 當作 props 這事情也是之後文章會常寫的寫法。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言