私は、再利用可能なフォームと入力コンポーネントを作成しようと、これまでに得てる次用いたフォームや入力要素を正しく
フォーム
import React from 'react'
import classNames from 'classnames/bind'
import styles from './style.scss'
const cx = classNames.bind(styles)
export default class Form extends React.Component {
constructor (props) {
super(props)
this.submitForm = this.submitForm.bind(this)
}
submitForm (e) {
e.preventDefault()
this.props.onSubmit()
}
render() {
return (
<form className={cx('Form')} onSubmit={this.submitForm}>
{this.props.children}
</form>
)
}
}
Form.propTypes = {
children: React.PropTypes.any.isRequired,
onSubmit: React.PropTypes.func.isRequired
}
入力
import React from 'react'
import classNames from 'classnames/bind'
import styles from './style.scss'
const cx = classNames.bind(styles)
export default class Input extends React.Component {
constructor (props) {
super(props)
this.state = {
value: this.props.value || ''
}
this.changeValue = this.changeValue.bind(this)
}
changeValue (e) {
this.setState({value: e.target.value})
}
render() {
return (
<div className={cx('Input')}>
<input
type={this.props.type}
value={this.state.value}
required={this.props.required}
onChange={this.changeValue}
placeholder={this.props.placeholder || ''}
noValidate />
</div>
)
}
}
Input.propTypes = {
type: React.PropTypes.string.isRequired,
value: React.PropTypes.string,
required: React.PropTypes.bool,
placeholder: React.PropTypes.string
}
それから、別のコンポーネント内でそれらを使用すると、HomePageComponent
<Form onSubmit={this.loginUser}>
<Input type='email' placeholder='email' />
<Input type='password' placeholder='password' />
<Input type='submit' value='Submit' />
</Form>
このすべてがうまく動作しますが、私は、入力値を取得し、あなたがInput
コンポーネントに値を格納する必要はありませんthis.state= { email: [value from input email], password: [value from password input] }
を役に立てば幸い? 。またはイベントを送信するときに値を入力したい場合 –
@Utroフォームの状態を把握しておくと便利です – Ilja