【发布时间】:2018-09-19 06:08:07
【问题描述】:
我正在尝试构建一个表单,对于给定的一组选项(存储在组件状态的数组中),您可以上传文件并为每个选项添加注释。表单是自定义的,但元素来自 Material UI。
代码看起来像这样(经过简化,去掉了其他不需要的数据)。
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 组件中。
它包含一个file 类型的简单input,但输入是隐藏的,只有按钮可见 - 示例取自官方材料 ui 文档 (https://material-ui.com/demos/buttons/ -> https://codesandbox.io/s/qzr18l41ow)
代码如下所示
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 方法中,第二个参数(索引)始终为零-因此对于我上传文件的任何选项-它始终附加到第一个选项。
现在,当我剥离按钮(删除它)并仅使用输入时 - 一切都按预期工作。
似乎按钮和标签正在禁用与传递的事件处理程序的正确连接。
有人知道如何解决这个问题吗?
【问题讨论】:
标签: javascript reactjs material-ui