<AddRecipe />
コンポーネントに<RecipeForm />
を実装しようとしています。後で同じフォームを更新アクションに再利用したいと思います。 レシピはまだリストに追加されません。反応の追加アクションと更新アクションのための再利用可能なフォームを実装するにはどうすればよいですか?
- 私のApp.jsに
handleAddRecipe
を定義しています。 - ここから
<AddRecipe />
コンポーネント - に渡し
は、私は、これらのコンポーネントに修正する必要があります<RecipeForm />
コンポーネントに渡しますか?
<AddRecipe />
コンポーネント:
class AddRecipe extends Component {
render() {
return (
<div>
<h2>Add New Recipe:</h2>
<RecipeForm
handleAddRecipe={this.props.handleAddRecipe}
/>
</div>
)
}
}
export default AddRecipe;
レポ:
export default class RecipeForm extends React.Component {
constructor(props) {
super(props);
this.state = {
url: this.props.url || '',
title: this.props.title || '',
description: this.props.description || '',
error: ''
};
}
onUrlChange = (e) => {
const url = e.target.value;
this.setState(() => ({ url }));
};
onTitleChange = (e) => {
const title = e.target.value;
this.setState(() => ({ title }));
};
onDescriptionChange = (e) => {
const description = e.target.value;
this.setState(() => ({ description }));
};
onSubmit = (e) => {
e.preventDefault();
if (!this.state.url || !this.state.title || !this.state.description) {
this.setState(() => ({ error: 'Please provide description and amount.'}));
} else {
this.setState(() => ({ error: ''}));
this.props.onSubmit({
url: this.state.url,
title: this.state.title,
description: this.state.description
});
}
}
render() {
const submitText = this.state.title ? 'Update' : 'Create' ;
return (
<div>
<form onSubmit={this.onSubmit}>
{this.state.error && <p>{this.state.error}</p>}
<input
type='text'
placeholder='picture url'
autoFocus
value={this.state.url}
onChange={this.onUrlChange}
/>
<input
type='text'
placeholder='title'
autoFocus
value={this.state.title}
onChange={this.onTitleChange}
/>
<input
type='text'
placeholder='description'
autoFocus
value={this.state.description}
onChange={this.onDescriptionChange}
/>
<button>Add Expense</button>
</form>
</div>
)
}
}
持つコンストラクタで、現在のスコープに関数をバインドするのonSubmit
type="submit"
あなたは正しい。私の現在のレシピフォームコンポーネントでポストを更新しました – karolis2017