我在一个表单中有多个用户输入,目前我正在打印到控制台。提交表单时,我希望在新页面上以单独的卡片呈现输入内容。
我需要在代码中添加/更改什么,才能使用户输入显示在卡片或任何html元素中,而不是呈现到控制台?
class Planning extends React.Component {
constructor() {
super()
this.state = {
title: '',
goal: '',
tech: '',
features: '',
details: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit(event) {
const {
title,
goal,
tech,
features,
details
} = this.state;
event.preventDefault();
console.log(`Plan
Title: ${title},
Goal: ${goal},
Technologies: ${tech},
Features: ${features},
Details: ${details}`)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label className="label-title">
Project Title:</label>
<input name="title" placeholder="Mental Health Guidance Website" id="title" type="text" onChange={this.handleChange}/>
</div>
<div>
<label className="label-goal">
Motivational Goal: </label>
<input name="goal" placeholder="To get a job as a Fullstack Web Developer" id="goal" type="text" onChange={this.handleChange}/>
</div>
<div>
...
<input class="submit" type="submit" value="Submit" />
</form>
)
}
}
发布于 2020-02-03 20:25:41
你可以使用集中化的单一状态来管理你的问题,如果你想将值传递到子组件中太深(如果你有太多的嵌套组件),你可以考虑使用context,如果你想只将值传递给直接子组件,那么你不必使用context或任何状态管理库,plane react就足以管理这种情况。
例如:
[Parent Component that keeps all values]
- Child 1 - Form Page - get all values and save it in the parent component
- Child 2 - Display Page - get values from the parent and display it here
如果您认为需要上下文,请参考React context,您可以使用它。
https://stackoverflow.com/questions/60038404
复制相似问题