Reactjs 在引导程序5上显示带有react挂钩的modal的问题
使用此组件时,我遇到控制台错误Reactjs 在引导程序5上显示带有react挂钩的modal的问题,reactjs,react-hooks,bootstrap-5,Reactjs,React Hooks,Bootstrap 5,使用此组件时,我遇到控制台错误 ParseExceptionsModal.jsx:18未捕获类型错误:无法读取null的属性“show” 这里是ParseExceptionsModal.jsx import { Modal } from 'bootstrap'; import React, { useState, useEffect, useRef } from 'react'; import ParseExceptions from './ParseExceptions'; const Pa
ParseExceptionsModal.jsx:18未捕获类型错误:无法读取null的属性“show”
这里是ParseExceptionsModal.jsx
import { Modal } from 'bootstrap';
import React, { useState, useEffect, useRef } from 'react';
import ParseExceptions from './ParseExceptions';
const ParseExceptionsModal = (props) => {
const [modal, setModal] = useState(null);
const parseExceptionModal = useRef();
useEffect(() => {
setModal(new Modal(parseExceptionModal.current), {
keyboard: false,
});
if (props.json.length > 0) {
modal.show(); //Here is the culprit. but why is it null?
}
}, []);
return (
<>
<div
className="modal fade"
tabIndex="-1"
role="dialog"
ref={parseExceptionModal}
aria-labelledby="parseExceptionModal"
aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">{props.title}</h5>
<button type="button" className="btn-close" onClick={() => modal.hide()} aria-label="Close">
{/*<span aria-hidden="true">×</span>*/}
</button>
</div>
<div className="modal-body">
<ParseExceptions json={props.json} />
</div>
<div className="modal-footer">
<button onClick={() => modal.hide()} type="button" className="btn btn-outline-secondary">
Dismiss
</button>
</div>
</div>
</div>
</div>
</>
);
};
export default ParseExceptionsModal;
从“bootstrap”导入{Modal};
从“React”导入React,{useState,useffect,useRef};
从“/ParseExceptions”导入ParseExceptions;
const ParseExceptionsModal=(道具)=>{
const[modal,setModal]=useState(null);
const parseExceptionModel=useRef();
useffect(()=>{
setModal(新模式(parseExceptionModal.current){
键盘:错,
});
如果(props.json.length>0){
modal.show();//罪魁祸首在这里。但为什么它为空?
}
}, []);
返回(
{props.title}
modal.hide()}aria label=“Close”>
{/*×;*/}
modal.hide()}type=“button”className=“btn btn大纲辅助”>
解雇
);
};
导出默认ParseExceptionsModal;
我的假设是setModal将为我初始化modal,而不是null。
我已经看到它是这样做的,但是如果我的json包含元素,我只需要显示这个模式。这就是为什么我认为在设置模式后,如果存在props.json.length>0
,我可以显示它
代码中有任何问题吗?或者是异步发生了什么,我需要等待bootsrap设置模式?不知道这里发生了什么
谢谢设置状态时不要实例化它。而是使用一个变量
useEffect(() => {
const modal = new Modal(parseExceptionModal.current, {keyboard: false})
setModal(modal)
modal.show()
},[])