我试图使用react引用将数据呈现到iframe中,但是我得到了
reference.current值为空。
我还检查了componentDidMount()中的值,但它给了我空值。当我在构造函数中设置参考值时。引用设置为"iframe“组件中的"PreviewEmailModal”组件。。
这就是为什么我获得当前值为null的原因。因此,一些人可以帮助我设置参考,iframe组件。
DOM版本- 16.4.2 React版本- 16.4.2
import React from "react";
import PropTypes from 'prop-types'
import { Button, Modal } from "react-bootstrap";
class PreviewEmailModal extends React.Component {
constructor() {
super();
this.textInput = React.createRef();
this.state = {
desktopPreview: true
};
}
render() {
this.props;
debugger
return (
<Modal
show={true} onHide={() => {
this.props.closeModal();
}}
className="preview-email-modal"
bsSize="lg">
<Modal.Header closeButton>
<Modal.Title>Preview</Modal.Title>
</Modal.Header>
<Modal.Body >
<div className="preview-icons">
<span className={this.state.desktopPreview ? "active-preview-icon margin-5" : ""}>
<i className="glyphicon glyphicon-blackboard" onClick={() => {
this.togglePreview();
}} />
</span>
<span className={this.state.desktopPreview ? "" : "active-preview-icon margin-5"}>
<i className="glyphicon glyphicon-phone" onClick={() => {
this.togglePreview();
}} />
</span>
</div>
<div>
<div className="text-center">
<iframe
title={"previewFrame"}
style={this.state.desktopPreview ?
{ width: "600px", height: "450px" } :
{ width: "320px", height: "450px" }}
id="previewIframe"
ref={(input) => {
this.textInput = input;
}}
/>
</div>
</div>
</Modal.Body>
</Modal>
);
}
componentDidUpdate() {
debugger
}
componentDidMount() {
const { current } = this.textInput;
//Here I get current value as null every time
const { data } = this.props;
if (current !== null) {
const doc = current.contentDocument;
doc.open();
doc.write(data);
doc.close();
}
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
}
togglePreview() {
this.setState({ desktopPreview: !this.state.desktopPreview });
}
}
PreviewEmailModal.propTypes = {
closeModal: PropTypes.func,
data: PropTypes.string
};
export default PreviewEmailModal;发布于 2019-05-02 07:40:02
您没有正确地使用Ref。而不是将回调传递给ref字段、pass实例。
或通过
ref={this.textInput}
而不是
ref={(input) => {this.textInput = input;}}
发布于 2020-01-14 23:54:46
当this.textInput实际上不在DOM上时,您可能会尝试引用它。
我通过添加这样的componentDidUpdate来解决这个问题:
componentDidUpdate() {
const { visible, emailHtml } = this.props;
if (visible) {
// this.iframe is my iframe ref
this.iframe.contentWindow.document.write(emailHtml);
}
}另外,我认为您不需要这一行来让参考文献发挥作用:
this.textInput = React.createRef();我也遇到了同样的问题(实际上我的组件也被称为PreviewEmailModal )。我甚至在PreviewEmailModal中也使用了一个非常类似的Modal组件。小世界!
发布于 2020-01-15 00:10:10
由于我不知道您的所有代码,所以建议将代码从componentDidMount转移到ref回调。请查看这里的丹·艾布拉莫夫的答案(componentDidMount called BEFORE ref callback)。
https://stackoverflow.com/questions/55947380
复制相似问题