我正在尝试构建一个表单,该表单对于给定的一组选项(以组件状态存储在数组中)使您可以上传文件并为每个选项添加注释。表单是自定义的,但元素来自于材料的用户界面。
代码看起来像这样(简化,去除了其他不需要的数据)。
public renderOptions() {
const { mdFiles } = this.state
return options.map((option, i) =>
<FileUpload
handleChange={(e) => {this.handleFileInputChange(e, i)}}
/>
<TextField
key={`option-${i}`}
name={option.name} */
type="text"
fullWidth
label={item}
placeholder={`Edit ${item}`}
value={option.note || option.originalNote}
onChange={(e) => this.handleChangeFileName(e, i)}
/>
)
}
我想对事件处理程序进行参数设置,以便除事件外还传递索引,因此我在便笺和/或上载的文件与选项之间建立了联系。
更改笔记可以按预期工作,但是问题出在FileUpload
组件中。
它包含类型为input
的简单file
,但输入是隐藏的,只有按钮可见-示例取自官方材料ui docs(https://material-ui.com/demos/buttons/-> { {3}})
代码看起来像这样
class FileUpload extends React.Component<Props, {}> {
public render() {
return (
<FileWrapper>
<input
accept={fileType}
id="file-upload"
type="file"
onChange={handleChange}
/>
<label htmlFor="file-upload" id="file-upload">
<Button
variant="contained"
component="span"
>
Upload
</Button>
</label>
</FileWrapper>
)
}
}
问题在于,在handleFileInputChange
方法中,第二个参数(索引)始终为零-因此,无论我上传文件的选项是什么,它始终附加在第一个选项上。
现在,当我剥离按钮(将其删除)并仅使用输入时-一切都会按预期进行。
似乎按钮和标签正在禁用与传递的事件处理程序的正确连接。
有人知道如何解决此问题吗?
答案 0 :(得分:0)
我发现了问题...
每个文件输入必须具有唯一的ID。在您的代码中,它们都具有id =“ file-upload”。这就是为什么所有按钮都会触发第一个输入的onchange处理程序的原因。
这是动态设置ID的修改版本。
class FileUpload extends React.Component {
render() {
const { id, handleChange } = this.props;
return (
<div>
<input id={id} type="file" onChange={handleChange} />
<label htmlFor={id} id={`${id}`}>
<Button variant="contained" component="span">
Upload
</Button>
</label>
</div>
);
}
}
实时示例: