/** * 子組件如何更改父組件的state呢? * 父組件傳遞下來的props不滿足要求,往往需要修改 * * * Author: shujun * Date: 2020-10-25 */ import React from 'react'; import {message} from 'antd'; import 'antd/dist/antd.css'; export default class Father extends React.Component{ render(){ return <div style={{width: '600px', paddingBottom: '20px', border: '1px solid red' }}> <h3>father:</h3> <p> 在父組件上調用子組件的方法,或者父組件訪問子組件的內容?<br/> 1. 給子組件傳遞一個方法:將子組件整個類全部指向this.sonObj變量<br/> 2. 子組件調用父組件傳入的函數,把自身賦給父組件 3. 父組件中this.sonObj就相當於子組件的this了,this.sonObj.xxx隨便調用子組件方法和state </p> {/* 3. 父組件中this.sonObj調用子組件方法 */} <button onClick={() => {this.sonObj.showSonInfo()}}> 調用子組件方法 </button> {/* 這么寫為什么是錯誤的呢?難道是this.child.showSonInfo還沒加載完成?而箭頭函數聲明寫法只是申明,要等點擊時候再觸發? */} {/* <button onClick={this.child.showSonInfo}>調用子組件方法</button> */} <button onClick={() => {message.success("子組件state: "+this.sonObj.state.name)}}> show 子組件state </button> {/* 1. 給子組件傳遞一個方法:將子組件整個類全部指向this.sonObj變量 */} <Son getSonFuncs={(son)=>{this.sonObj=son}} /> </div> } } class Son extends React.Component { state = { "name": "sbjun" }; componentDidMount(){ // 2. 子組件調用父組件傳入的函數,把自身賦給父組件 this.props.getSonFuncs(this); } showSonInfo = ()=>{ message.info("我是子組件Son的方法"); } render(){ const name = this.state.name; return <div style={{border: '1px solid green', marginTop: '20px'}}> <h3>Son:</h3> <button onClick={this.showSonInfo}>子組件事件</button><br/> <input value={name} onChange={(e)=>{this.setState({name: e.target.value})}}/> state: name -- {name} </div> } }
運行效果: