【react】form部品を共通化するときのひな形
はじめに
ES6でのシンプルなものだけど共通化するとしたらこんな感じだろうか
呼び出し側
import React from "react";
import FormPart from "./FormPart.jsx";
export default class Sample extends React.Component
{
constructor(props)
{
super(props);
this.state = {
title: "",
description: ""
};
}
onChange(e)
{
this.setState({
[e.target.name]: e.target.value
});
}
render()
{
let onSave = () => {
// => this.stateで入力値取得
};
return (
<div>
<FormPart {...this.props}
{...this.state}
onChange={this.onChange.bind(this)}
/>
<button type="button" onClick={onSave}>Save</button
</div>
);
}
}共通フォーム(呼ばれる側)
import React from "react";
export default class FormPart extends React.Component
{
render()
{
return (
<div>
<div>
<label>タイトル</label>
<input type="text"
name="title"
value={this.props.title}
onChange={this.props.onChange.bind(this)}
/>
</div>
<div>
<label>本文</label>
<input type="text"
name="description"
value={this.props.description}
onChange={this.props.onChange.bind(this)}
/>
</div>
</div>
);
}
}以上です