提交表格数据后,我只能在渲染组件时遇到麻烦。
所以我有一个具有基本渲染的应用程序:
(<div>
<form onSubmit={this.onSubmit.bind(this)}>
</form>
<Results/>
</div>);
想法是onSubmit仅在提交时才会将一些数据转储到Results
组件中。
现在我要说实话,该应用在其状态下已经具有值:
this.state = {
length : 0,
timeInSeconds: 0
}
因此,我只希望它在用户单击“提交”按钮并且执行onSubmit方法时渲染或重新渲染该对象。
很抱歉,这不是我想要的,但是任何建议或指导都很棒!
谢谢, 凯莉
答案 0 :(得分:3)
您可以在onSubmit结束时标记完成状态并有条件地呈现结果吗?像这样:
this.state = {
length : 0,
timeInSeconds: 0,
isSubmitted: false
}
onSubmit(e) {
// Do something
this.setState({isSubmitted: true})
}
然后放置一个条件以呈现结果。
(<div>
<form onSubmit={this.onSubmit.bind(this)}>
</form>
{this.state.isSubmitted && <Results/>}
</div>);
答案 1 :(得分:0)
您需要执行以下操作:
答案 2 :(得分:0)
这就是我要做的。我确实在飞行中,但是我很确定这就是您所需要的。我希望是正确的:)让我知道是否有帮助
import React, { Component } from 'react';
import Results from './results';
class FormData extends component {
constructor(props) {
super(props);
this.state = {
name: '',
age: null,
submitted: false
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
// Let's 1st make a onChane function and get the form data
onChange(e) {
this.setState({ [e.target.name]: e.target.value }); // Getting access to entered values
}
// Let's make an onSubmit function
onSubmit(e) {
e.preventDefault(); // Here we prevent the default browser behavior
this.setState({isSubmitted: true}); // Let's set the new 'submitted state to TRUE
// Gathering data in order to pass it to the <Results /> component
const formData = {
name: this.state.name,
age: this.state.age
};
this.props.makeResultsData(formData); // Passing the data down as props
}
// Let's render the necessary data including the results component
render() {
return (
// Little bit of destructuring
// This is equal to const submitted = this.state.submitted
{ submitted } = this.state;
<div className="container">
<form onSubmit={this.onSubmit}>
<label>
Name:
placeholder="Enter your name"
name="name"
value={this.state.name}
onChange={this.onChange}
</label>
<label>
Age:
placeholder="Enter your age"
name="age"
value={this.state.age}
onChange={this.onChange}
</label>
// Let's finally SUBMIT our form and change the states 'submitted' value to TRUE
<input type="submit" value="Submit" />
</form>
// With conditional rendering ,we can now display our <Results /> component, like this
{this.state.isSubmitted && <Results/>} // So, if submitted = true, render the Results component
</div>
);
}
}