假设页面包含多阶段表单,表单的第一阶段包含名称的输入字段,第二阶段包含文件的输入,onChange设置名称和文件的状态值,但是当我们像第一个那样来回移动时阶段到第二阶段和第二阶段,我们可以保留输入类型名称的值,但是如何保留输入类型文件的值。
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
pageone: true,
pagetwo: false,
pagethree: false,
pageonedata: "",
pagetwodata: "",
pagethreedata: ""
};
this.nextPage = this.nextPage.bind(this);
this.prevPage = this.prevPage.bind(this);
this.togglePage = this.togglePage.bind(this);
}
prevPage() {
if (this.state.pagetwo === true) {
this.setState({
pageone: !this.state.pageone,
pagetwo: !this.state.pagetwo
});
} else if (this.state.pagethree === true) {
this.setState({
pagethree: !this.state.pagethree,
pagetwo: !this.state.pagetwo
});
}
}
nextPage() {
if (this.state.pageone === true) {
this.setState({
pageone: !this.state.pageone,
pagetwo: !this.state.pagetwo
});
} else if (this.state.pagetwo === true) {
this.setState({
pagetwo: !this.state.pagetwo,
pagethree: !this.state.three
});
}
}
togglePage() {
this.setState({
pageone: !this.state.pageone,
pagetwo: !this.state.pagetwo
});
}
handleChange = e => {
this.setState({ ...this.state, [e.target.name]: e.target.value });
};
handleChange = e => {
this.setState({ ...this.state, [e.target.name]: e.target.files[0] });
};
render() {
return (
<div style={{ margin: "250px 500px" }}>
{this.state.pageone && (
<form>
<label>
<h4>page one</h4>
</label>
<input
type="text"
name="pageonedata"
value={this.state.pageonedata}
onChange={this.handleChange}
/>
</form>
)}
{this.state.pagetwo && (
<form>
<label>
<h4>page two</h4>
</label>
<input
type="file"
name="pagetwodata"
value={this.state.pagetwodata}
onChange={this.handleFile}
/>
</form>
)}
{this.state.pagethree && (
<form>
<label>
<h4>page three</h4>
</label>
<input
type="text"
name="pagethreedata"
value={this.state.pagethreedata}
onChange={this.handleChange}
/>
</form>
)}
<br />
<button
type="submit"
onClick={this.prevPage}
disabled={this.state.pageone ? true : false}
>
previous
</button>{" "}
<button
type="submit"
onClick={this.nextPage}
disabled={this.state.pagethree ? true : false}
>
next
</button>{" "}
<button
type="submit"
onClick={this.togglePage}
disabled={this.state.pagethree ? false : true}
>
finish
</button>
</div>
);
}
}
export default App;
答案 0 :(得分:2)
您不能以编程方式将文件插入输入元素,只有用户才能这样做,因此将文件保留在输入中的最佳方法是在表单上有条件地设置display:none;
而不是删除它来自DOM。
示例
class App extends Component {
// ...
handleFile = e => {
this.setState({ ...this.state, [e.target.name]: e.target.files[0] });
};
render() {
return (
{/* ... */}
<form style={{ display: this.state.pagetwo ? 'block' : 'none' }}>
<label>
<h4>page two</h4>
</label>
<input
type="file"
name="pagetwodata"
value={this.state.pagetwodata}
onChange={this.handleFile}
/>
</form>
{/* ... */}
);
}
}