AdSense

網頁

2021/7/22

React 在父組件及子組件間傳遞資料 pass data between parent and children components

React Parent Component(父組件)與Child Component(子組件)間傳遞資料的方式如下。


下面範例在App建立三個Component結構如下,父組件Block中有兩個子組件InputDisplay

App
└─ Block
    ├── Input
    └── Display

Input<input/>文字輸入欄位組件,內容改變時會呼叫change事件的處理方法handleChange(event)將欄位值傳給props.toBlockBlock父組件的callback方法receiveValueFromInput()做為輸入參數。

Block.receiveValueFromInput()透過Input.toBlock收到欄位值參數後呼叫Block.setValue()把值設定到Block.state.inputValue,因Block狀態改變會重新呼叫Block.render()同時把更新的Block.state.inputValue(即欄位文字內容)作為Displayprops.value(即<Display value={this.state.inputValue}/>)並取出為段落元素<p>的內容。

App.js

import { Component } from 'react'
import './App.css';

function App() {
  return <Block/>
}

class Block extends Component {

  constructor(props) {
    super(props)
    this.state = {inputValue: ''}

    this.receiveValueFromInput = this.receiveValueFromInput.bind(this)
  }

  receiveValueFromInput(valueFromInput) {
    this.setState({inputValue: valueFromInput})
  }

  render() {
    return (
      <div>
        <Input toBlock={this.receiveValueFromInput}/>
        <Display value={this.state.inputValue}/>
      </div>
    )
  }

}

class Input extends Component {

  constructor(props) {
    super(props)
    this.state = {value: ''};
    this.handleChange = this.handleChange.bind(this)
  }

  render() {
    return <input value={this.state.value} onChange={this.handleChange}/>
  }

  handleChange(event) {
    this.setState({value: event.target.value})
    this.props.toBlock(event.target.value)
  }
}

class Display extends Component {

  constructor(props) {
    super(props)
    this.state = {value: ''}
  }

  render() {
    return <p>{this.props.value}</p>
  }
}

export default App;



參考github



沒有留言:

AdSense