父组件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; }