当一个模态引用打开时,当我试图访问它时,我有问题。
下面是我的包装类。
ModalWrapper
import * as React from 'react';
import MyModal from './MyModal'
import * as ReactDOM from "react-dom";
export interface IModalWrapperProps {
}
export class ModalWrapper extends React.PureComponent<IModalWrapperProps, {}> {
constructor() {
super();
}
/**
* EDITED HERE
*/
handlePrint = (refObj) => {
//Getting the ref of the MyMoal component but when I trying to log the data key it is undefined
console.log(refObj); //successfully logs the ref object of MyModal component.
const refVal = refObj.data;
const node = ReactDOM.findDOMNode(refVal);
console.log(node) // logging null still
}
renderDivTag = () => {
return (
<div>
<h1>Hello Modal</h1>
</div>
)
}
render() {
return (
<MyModal id="test-modal" onPrint={this.handlePrint} showComponent={this.renderDivTag()} />
<button onClick={() => showHelloModal('test-modal')} />
)
}
}MyModal组件
import * as React from 'react';
import { Modal } from 'react-bootstrap';
import { connect } from 'react-redux';
export interface IMyModalProps {
modalID: string;
id: string;
showComponent: React.ComponentClass;
onPrint: (ref) => void;
}
export class MyModalImpl extends React.PureComponent<IMyModalProps, {}> {
constructor() {
super();
}
/**
* EDITED HERE
*/
refValue;
handlePrint = () => {
return this.props.onPrint(this.refValue);
}
render() {
if (this.props.modalID !== this.props.id) {
return <div></div>;
}
return (
<Modal className="print-preview-outer" show={true} >
<Modal.Header closeButton>
<Modal.Title>Print Preview</Modal.Title>
</Modal.Header>
<Modal.Body className="print-preview">
<div
/**
* EDITED HERE
*/
ref=((value) => this.refValue = value)
style={{ width: '597px', background: 'white', margin: 'auto' }}
id="print-preview"
>
{this.props.showComponent}
</div>
</Modal.Body>
<button onClick={this.handlePrint}>Print</button>
</Modal >
)
}
}
export function mapStateToProps(state) {
return {
modalID: state.get('modalID')
}
};
export const MyModal = connect<{}, {}, IMyModalProps>(mapStateToProps)(MyModalImpl)因此,当我单击按钮时,showHelloModal方法在键modalID上设置一个值,然后比较模态id,如果两者相等,则显示模态。
现在我要做的是,我需要在我的DOMNode组件中的MyModal组件在显示模式后打印Hello单词。
如何使用ref获得对DOM节点的引用。如果我使用的是document.getElementById('print-preview'),我可以访问该模式的DOM节点,但我希望使用ref。
另外一件事是,当我在我的this.refs组件中记录ModalWrapper时,我在控制台中得到一个对象,如下所示
任何帮助都是必要的。
发布于 2021-09-17 10:37:10
useRef钩子不会在modals中工作,因为组件将挂载,但是jsx将不会呈现,直到你使显示道具变为真。useRef本质上是异步的,这就是为什么在声明时它将current设置为null,但是在将它赋值给任何元素之后,ref获得了它的值。但是如果是情态的话,情况就不同了。在这里,元素不是立即注册的,而是在模态显示支柱被设置为true之后。
为了解决这一问题,使模型的显示支柱始终为真,并使整个组件动态显示/隐藏。例如:
const Child=()=>{
const customRef=useRef(null);
return(
<Modal show={true}>
<Modal.Body>
<input ref={customRef} type="text"/>
</Modal.Body>
</Modal>
);
}
const Parent=()=>{
const [show,setShow]=useState=(false)
return(
<>
<button onClick={()=>setShow(!show)}>Show/Hide Popup</button>
{
show?<Child/>:null
}
</>
)
}这肯定会解决在Modal弹出窗口中使用useRef的问题。
https://stackoverflow.com/questions/47474829
复制相似问题