【发布时间】:2018-12-30 04:41:34
【问题描述】:
我正在编写我的第一个 React 应用程序,并且真的很难做一些非常基本的事情。
我有一个 Input 组件,它有一个处于状态的数组,当它有两个数字时,它会将它们和一个唯一 ID 作为对象发送到将对象存储在数组中的父组件。
这一切都很好,我可以做到。问题是之后清除输入。
据我了解,当我执行 on Change 时,我需要将输入的值存储在组件状态(在数组中)中。然后将这些值用于提交表单。
但是,如果输入从状态中获取值,则它们需要在渲染时具有值,这是我不想要的。我只希望它们在 我在输入中输入了一些内容之后有一个值。我尝试在提交后使用 setState 将 inputTable 替换为空数组,但这仍然没有改变值。
这是代码 - 重申一下,我想在提交数组后找到一种方法来清除输入。目前它一直说我正在将一个不受控制的组件更改为一个受控的组件,我理解,但我不明白我的意思是什么
请相信我已经尝试自己解决这个问题,查看有关表单和输入的 MDN 文档,但我真的没有得到任何结果。非常感谢您的帮助。
import React, { Component } from 'react';
class Input extends Component {
constructor(props) {
super(props)
this.state = {
inputTable: [],
uniqueId: 1
}
this.handleChange = this.handleChange.bind(this);
this.sendTables = this.sendTables.bind(this);
}
async handleChange(e) {
e.preventDefault();
await this.setState({
inputTable: [
...this.state.inputTable, e.target.value
]
})
console.log(this.state.inputTable)
// how do I handle this onChange correctly?
}
async sendTables(e) {
e.preventDefault();
this.props.submitTable(this.state.inputTable, this.state.uniqueId);
let newArray = [];
await this.setState({
inputTable: newArray,
uniqueId: this.state.uniqueId + 1
})
console.log(this.state.inputTable)
// how can I clear the inputs?
}
render() {
return (
<div className="Input">
<form action="" onSubmit={this.sendTables}>
<input required type="number" name="value0" placeholder="a number..." onChange={this.handleChange} value={this.state.inputTable[0]} />
<span>X</span>
<input required type="number" name="value1" placeholder="multiplied by..." onChange={this.handleChange} value={this.state.inputTable[1]}/>
<input type="submit" value="Add times table" />
</form>
</div>
);
}
}
export default Input;
父组件:
import React, { Component } from 'react';
import Input from './Input/Input';
class InputTimesTables extends Component {
constructor() {
super();
this.state = {
tables: [],
noInputs: 1
}
this.pushToTables = this.pushToTables.bind(this);
}
addInput() {
// this will be used to add an additional input
// it will increment no. inputs
}
async pushToTables(arr, id) {
let newTimesTable = {
timesTable: arr,
uniqueId: id
}
await this.setState({
tables: [...this.state.tables, newTimesTable]
})
// console.log(`The ITT state looks like:`, this.state.tables);
//this will take the two numbers in the array from the Input
// and push them to the tables array
// it won't run unless there are two numbers in that array
console.log('The main state array now looks like this: ', this.state.tables)
}
// clearTables(id){
// console.log(`splicing array no ${id}`);
// let newArray = this.state.tables;
// newArray.splice(id, 1);
// this.setState({
// tables: newArray
// })
// console.log(this.state.tables);
// // console.log(`The ITT state looks like:`, this.state.tables);
// }
render() {
return (
<div>
<Input submitTable={this.pushToTables}/>
<h3>Currently being tested on:</h3>
<ul>
</ul>
</div>
);
}
}
export default InputTimesTables;
非常感谢。
【问题讨论】:
-
你能分享你的父组件吗?
-
是的,现在可以了,谢谢
标签: javascript reactjs forms input