【发布时间】:2021-10-11 12:51:14
【问题描述】:
我有 Formio 的自定义组件 Slider。函数attachReact() 将我的自定义组件附加到Formio 提供的元素内。附加完成后,我应该立即从ReactDOM.render() 获取该组件的实例,但我没有。稍后,Formio 使用该实例来更改我需要的字段值。
如何确保我从ReactDOM 获得的实例立即返回?我意识到将来会从 React 中删除该功能,但在 Formio 使用它时我仍然需要它。
import { ReactComponent } from "@formio/react";
import React from "react";
import ReactDOM from "react-dom";
import settingsForm from "./Slider.settingsForm";
class SliderCustomComp extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value,
};
}
setValue = (v) => {
this.setState({ value: v }, () => this.props.onChange(this.state.value));
};
render() {
return (
<div className="w-full" id="custcomp">
<input
className="w-full focus:outline-none"
type="range"
min={this.props.component.minRange}
max={this.props.component.maxRange}
value={this.state.value}
onChange={(e) => {
this.setValue(e.target.value);
}}
/>
<span>{this.state.value}</span>
</div>
);
}
}
export default class Slider extends ReactComponent {
constructor(component, options, data) {
super(component, options, data);
}
static schema() {
return ReactComponent.schema({
type: "sliderCustomComp",
label: "Default Label",
});
}
static editForm = settingsForm;
attachReact(element) {
console.log(element);
const instance = ReactDOM.render(
<SliderCustomComp
component={this.component} // These are the component settings if you want to use them to render the component.
value={this.dataValue} // The starting value of the component.
onChange={this.updateValue} // The onChange event to call when the value changes.}
/>,
element
);
console.log("instance in attachReact", instance);
return instance;
}
}
【问题讨论】: