index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css'
class ParentCom extends React.Component {
constructor(props) {
super(props)
}
render() {
return ( <
div onClick = { this.parentEvent } >
<
div className = "child" >
<
h1 > helloworld < /h1>
<
/
div >
<
button onClick = {
(e) => { this.parentEvent1('msg:123', e) }
} > 提交 < /button> < /
div >
)
}
parentEvent = (e) => {
console.log(e)
e.preventDefault()
}
parentEvent1 = (msg, e) => {
console.log(msg)
e.preventDefault(e)
}
}
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"))
运行结果