我正在React中创建一个表单,并希望在不刷新页面的情况下接收用户输入。当我在表单提交中调用元素时,该值返回未定义,但元素本身保存数据。任何帮助将不胜感激。
var afterSubmission = (event) => {
event.preventDefault();
console.log(document.getElementsByName("startDate"))
setStartDate(document.getElementsByName("startDate").value)
console.log(startDate)
};
return (
<>
<div>
<form onSubmit={afterSubmission}>
<input className="startDate" placeholder="Enter a start date (e.g. 2019-12-16)" type="text" name="startDate" />
<input className="endDate" placeholder="Enter an end date (e.g. 2019-12-18)" type="text" name="endDate" />
<input className="export" type="submit" value="Submit" />
</form>
</div>
</>
)
答案 0 :(得分:0)
更改为:
setStartDate(document.querySelector(".startDate").value)
解决了该问题并返回输入的值。谢谢萨蒂夫
答案 1 :(得分:0)
您可以使用受控组件并维护单一事实来源
constructor(props) {
super(props);
this.state = {
startDate: { value: "" },
endDate: { value: "" }
};
}
handleInputChange = e => {
e.preventDefault();
const target = e.target;
const inputName = target.name;
const inputValue = target.value;
this.setState({ [inputName]: { value: inputValue } });
};
afterSubmission = e => {
event.preventDefault();
console.log(this.state.startDate.value);
};
render() {
return (
<div>
<form onSubmit={afterSubmission}>
<input
className="startDate"
placeholder="Enter a start date (e.g. 2019-12-16)"
type="text"
name="startDate"
onChange={this.handleInputChange}
value={this.state.startDate.value}
/>
<input
className="endDate"
placeholder="Enter an end date (e.g. 2019-12-18)"
type="text"
name="endDate"
onChange={this.handleInputChange}
value={this.state.endDate.value}
/>
<input className="export" type="submit" value="Submit" />
</form>
</div>
);
}