gpt4 book ai didi

javascript - 如何访问组件的引用?

转载 作者:行者123 更新时间:2023-11-30 20:33:39 24 4
gpt4 key购买 nike

我正在使用 react-jsonschema-form从 JSON 模式创建表单。在 this JSFiddle example ,我创建了一个由单个 <input type="file"> 组成的表单字段。

FileWidget 的实例组件用于呈现此字段,正如您在 the source code 中看到的那样, 这存储了对 <input> 的引用this.inputRef 中的元素.

我想使用此 ref 向输入字段添加其他属性,但我不知道如何从 componentDidMount 访问该 ref MyForm的方法| ?

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 />
)
}
};

最佳答案

您可以从同一个库中导入并使用 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} ... />

Edit oq7xqoz46q

旁注:

这不是库公开内部引用的一种非常直观的方式。应该是:

<input
ref={ref => {
if (this.props.setInputRef) {
this.props.setInputRef(ref);
}
}}
/>

然后你可以用

得到 inputRef
<FileWidget setInputRef={ref => { this.inputRef = ref } ... /> 

关于javascript - 如何访问组件的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com