将一个函数作为 props 传递给子组件
index.js
import React from 'react'
import ReactDOM from 'react-dom'
const UserNameInput = ({ getName }) => {
return (
<input
onInput={function (e) {
getName(e.target.value)
}}
/>
)
}
class UserName extends React.Component {
constructor() {
super()
this.state = {
name: '',
}
}
getName = name => {
this.setState(() => ({ name }))
}
render() {
return (
<div>
<UserNameInput getName={this.getName} />
<div>{this.state.name}</div>
</div>
)
}
}
ReactDOM.render(<UserName />, document.getElementById('root'))