如何从表单组件获取状态/值?

编程入门 行业动态 更新时间:2024-10-24 21:23:55
本文介绍了如何从表单组件获取状态/值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑具有如下形式的组件:

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> ) } }

更多推荐

如何从表单组件获取状态/值?

本文发布于:2023-10-09 18:38:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476464.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   组件   状态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!