我正在使用react jsonschema-格式从JSON模式创建一个表单。在这个JSFiddle示例中,我创建了一个由单个<input type="file">
字段组成的表单。
FileWidget组件的一个实例用于呈现这个字段,正如您在源代码中看到的那样,它将一个参考文件存储到this.inputRef
中的<input>
元素。
我想使用这个ref向输入字段添加额外的属性,但是我想不出如何从MyForm
的MyForm
方法访问ref
JSFiddle示例中组件的源代码是:
class MyForm extends React.Component {
constructor(props) {
super(props);
this.uiSchema = {};
this.schema = {
"title": "Files",
"type": "object",
"properties": {
"file": {
"type": "string",
"format": "data-url",
"title": "Single file"
},
}
}
};
componentDidMount() {
// How can I get access to the FileWidget's inputRef property here?
}
render() {
return (
<Form
schema={this.schema}
uiSchema={this.uiSchema}
liveValidate />
)
}
};
发布于 2018-04-27 18:07:37
您可以从同一个库导入和使用FileWidget
来获取参考资料:
import FileWidget from 'react-jsonschema-form/lib/components/widgets/FileWidget'
constructor(props) {
...
this.widgets = {
FileWidget: (props) => (
<FileWidget
{...props}
ref={ref => {
this.fileWidget = ref;
}}
/>
)
};
}
componentDidMount() {
console.log(this.fileWidget.inputRef);
}
<Form widgets={this.widgets} ... />
西德诺特:
对于一个库来说,这并不是一种非常直观的公开内部引用的方法。它应该是:
<input
ref={ref => {
if (this.props.setInputRef) {
this.props.setInputRef(ref);
}
}}
/>
然后你就可以用inputRef
<FileWidget setInputRef={ref => { this.inputRef = ref } ... />
https://stackoverflow.com/questions/50066621
复制相似问题