本文介绍了如何从表单组件获取状态/值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑具有如下形式的组件:
Consider having form component like:
export default class Form extends React.Component { constructor (props) { this.state = { email: '' } this.onChange = this.onChange.bind(this) } onChange(event) { this.setState({ email: event.target.value }) } render () { return ( <div> <h2>{this.props.title}</h2> <form className={cx('Form')} onSubmit={this.props.onSubmit}> <input className={cx('Form-email')} type='email' placeholder='email' value={this.state.email} onChange={this.onChange} /> <input className={cx('Form-btn')} type='submit' value='sign up' /> </form> </div> ) } }然后我将在应用程序中的其他位置使用此<Form onSubmit={this.someFunction} />组件,让我们在HomePage组件内部进行假设.在该主页中,我将有this.someFunction会在表单到达顶点时执行,如何将表单的值/状态传递给它?
I would then use this <Form onSubmit={this.someFunction} /> component elsewhere within my app, lets assume inside HomePage component. Inside that home page I would have this.someFunction that executes when form is summited, how can I pass form value / state to it?
推荐答案在您的组件中创建一个回调,该回调将以状态为参数调用发送到Form的函数.
Create a callback in your component that will call the function sent to Form with the state as parameter.
export default class Form extends React.Component { constructor (props) { this.state = { email: '' } this.onChange = this.onChange.bind(this) this.onSubmit = this.onSubmit.bind(this) } onChange(event) { this.setState({ email: event.target.value }) } onSubmit() { this.props.onSubmit(this.state); } render () { return ( <div> <h2>{this.props.title}</h2> <form className={cx('Form')} onSubmit={this.onSubmit}> <input className={cx('Form-email')} type='email' placeholder='email' value={this.state.email} onChange={this.onChange} /> <input className={cx('Form-btn')} type='submit' value='sign up' /> </form> </div> ) } }更多推荐
如何从表单组件获取状态/值?
发布评论