import React from 'react';
import ReactDOM from 'react-dom';
import './App.css'
class ParentCom extends React.Component {
constructor(props) {
super(props)
this.state = {
childData: null
}
}
render() {
return ( <
div >
<
h1 > 子元素传递给父级 { this.state.childData } < /h1> <
ChildCom setChildData = { this.setChildData }
/ > < /
div >
)
}
setChildData = (data) => {
this.setState({
childData: data
})
}
}
class ChildCom extends React.Component {
constructor(props) {
super(props)
this.state = {
msg: "geyao"
}
}
render() {
let sendData = null
return ( <
div >
<
button onClick = { this.sendData } > 传递helloworld给父元素 < /button> <
button onClick = {
() => { this.props.setChildData('直接调用') } } > 传递helloworld给父元素 < /button> <
/
div >
)
}
sendData = () => {
console.log(this.state.msg)
console.log(this.props.setChildData(this.state.msg))
}
}
//console.log("这是渲染函数")
ReactDOM.render( < ParentCom / > , document.querySelector("#root"))
运行结果