父組件js
import React, { Component } from 'react'; import Son from './Son' import './Father.css' class Father extends Component { constructor(props) { super(props); this.state = { sonValue: null } } render() { let {sonValue} = this.state; return ( <div className="father"> <h1>我是父組件</h1> <p>接收到的數據為:{sonValue}</p> <Son onSend={this.handleAction}/> </div> ); } handleAction = (data)=>{ console.log('handleAction執行了'); this.setState({sonValue: data}); } } export default Father;
子組件js
import React, { Component } from 'react'; import './Son.css' class Son extends Component { constructor(props) { super(props); this.state = { inputVal: '' } } render() { // console.log(this.props.onSend); // this.props.onSend(1,2,3,4); let {inputVal} = this.state; return ( <div className="son"> <h1>我是子組件</h1> <input type="text" value={inputVal} onChange={this.changeAction}/> <button onClick={()=>{ //調用父組件的函數,傳入參數,實現子組件向父組件的傳值 this.props.onSend(inputVal); }}>發送</button> </div> ); } changeAction = (ev)=>{ this.setState({inputVal: ev.target.value}); } } export default Son;
父組件css
.father{ padding: 50px; background: lemonchiffon; }
子組件css
.son{ padding: 30px; background: lightblue; }