好吧,所以我有一个表单,上面有用于图像的文件输入(并且在提交前预览了图像),但是只有第一个输入更新(无论我使用哪个输入来放置图像)。
以下是复制步骤:
这是我的拖放区组件代码:
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的新手,所以任何解释都将有助于加载。谢谢!
答案 0 :(得分:1)
React不是问题,而是HTML绑定。您需要为输入框和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>
);
}
}