好吧,我有一个表单,上面有图像的文件输入(并且在提交之前预览图像),但只有第一个输入更新(无论我使用哪个输入来放置图像)。
以下是重现步骤:
- 点击“添加问题”按钮两次或多次
- 点击(因为还无法放置)第二个放置区并上传文件。
- 看到第一个拖放区更新,而不是第二个
这是我的放置区组件的代码:
class DropZone extends Component {
constructor(props){
super(props)
this.state = {
file: "",
fileId: uuid()
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({
file: URL.createObjectURL(event.target.files[0])
})
//document.getElementsByClassName("dropZone").style.backgroundImage = 'url(' + this.state.file + ')';
}
render() {
return (
<div >
<input type="file" id="file" name="file" class="inputFile" onChange={this.handleChange}/>
<label key={uuid()} for="file" value={this.state.file} onchange={this.handleChange}>
<div class="dropZone" key={uuid()}>
Drop or Choose File
<img src={this.state.file} id="pic" name="file" accept="image/*"/>
</div>
</label>
<div>
</div>
</div>
);
}
}
我是 React 和 JS 的新手,所以任何解释都会有帮助。谢谢!
最佳答案
这不是 React 的问题,而是 HTML 绑定(bind)的问题。您需要为输入框和 label htmlFor
属性提供唯一的 id。我已经更新了下面的代码。以及您的代码沙箱 -> https://codesandbox.io/s/kkj7j61noo
class DropZone extends Component {
constructor(props){
super(props)
this.state = {
file: "",
fileId: uuid()
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({
file: URL.createObjectURL(event.target.files[0])
})
//document.getElementsByClassName("dropZone").style.backgroundImage = 'url(' + this.state.file + ')';
}
render() {
const uniqueId = this.state.fileId;
return (
<div >
<input type="file" id={uniqueId} name={uniqueId} class="inputFile" onChange={this.handleChange}/>
<label key={uuid()} htmlFor={uniqueId} value={this.state.file}>
<div class="dropZone" key={uuid()}>
Drop or Choose File
<img src={this.state.file} id="pic" name="file" accept="image/*"/>
</div>
</label>
<div>
</div>
</div>
);
}
}
关于javascript - 文件输入未正确更新状态 React?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51562553/