创建对象并将其传递给父组件的最佳做法是什么?我的代码在下面运行的很好,但似乎我必须在这里扔很多东西,只是为了提交一个带有2个字段的简单表单。创建对象并将其传递给父组件的最佳做法是什么?
我创建的构造函数,
监听事件,
结合事件,
更新和传递状态App.js
是,这是最好的做法?:
class AddFishForm extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
amount: ''
};
this.onTitleChange = this.onTitleChange.bind(this);
this.onAmountChange = this.onAmountChange.bind(this);
}
onTitleChange = (e) => {
const title = e.target.value;
this.setState(() => ({ title }));
};
onAmountChange = (e) => {
const amount = e.target.value;
this.setState(() => ({ amount }));
};
createFish(event) {
event.preventDefault();
this.props.addFish({
url: this.state.url,
title: this.state.title
});
}
render() {
return (
<Segment>
<Form onSubmit={(e) => this.createFish(e)}>
<Form.Group >
<Form.Input
type='text'
placeholder='picture url'
autoFocus
value={this.state.title}
onChange={this.onTitleChange}
width={6}
/>
<Form.Input
type='text'
placeholder='title'
autoFocus
value={this.state.amount}
onChange={this.onAmountChange}
width={6}
/>
</Form.Group >
<Button fluid type='submit'>Submit</Button>
</Form>
</Segment>
)
}
}
感谢您的解决方案。但是,我不是100%确定如何在我的代码上下文中实现这一点。你能提供与我的案例更相关的代码吗? – karolis2017
感谢您的更新,这完美无缺的代码! – karolis2017