Reactjs react模态不能使用useState钩子打开
我有一个呈现Reactjs react模态不能使用useState钩子打开,reactjs,Reactjs,我有一个呈现反应模式的组件,我的问题是反应模式没有打开modalFileNameOpenuseState属性设置不正确 const [modalFileNameOpen, setmodalFileNameOpen] = useState(false) const handleFileNameChangeClick = () => { console.log(modalFileNameOpen) // set to false setmodalFileNameOpen
反应模式
的组件,我的问题是反应模式
没有打开modalFileNameOpen
useState
属性设置不正确
const [modalFileNameOpen, setmodalFileNameOpen] = useState(false)
const handleFileNameChangeClick = () => {
console.log(modalFileNameOpen) // set to false
setmodalFileNameOpen(true) // this does not set the `modalFileNameOpen` to true.
console.log(modalFileNameOpen) // is still false
}
return (
<div className="container-fluid">
<input type="button" className="btn" onClick={handleFileNameChangeClick} value="Rename File"></input>
<ModalFileName modalFileNameOpen={modalFileNameOpen} />
</div>
)
这是一个你似乎想要达到的最低限度的例子 这是将状态向上拉到父级并将处理程序函数向下传递到子级的基本说明。在您的代码中,您试图通过基于父级的状态在子级中声明一个新状态来实现这一点,这将导致不必要的重复和可能的状态冲突 我们声明模态状态和setter以及一个基本处理函数:
const [openModal, setOpenModal] = useState(false);
const toggleModal = () => {
setOpenModal(!openModal);
}
然后,我们根据当前状态值有条件地呈现模态组件。如果openModal
为false,则呈现按钮以打开它,否则呈现模态组件并将处理程序函数toggleModal
作为道具传递给它
// if openModal is false render the button, else render our modal
{!openModal ?
<button type="button" onClick={toggleModal}>Open Modal</button>
: <Modal handler={toggleModal} />
}
工作示例
正文{
填充:0;
保证金:0;
}
.集装箱{
位置:相对位置;
高度:100vh;
宽度:100vw;
背景:灰色;
}
.莫代尔{
高度:50vh;
宽度:50vw;
位置:绝对位置;
最高:25%;
左:50%;
转化:translateX(-50%);
背景色:浅绿色;
}
const{useState}=React;
函数App(){
const[openModal,setOpenModal]=useState(false);
常量toggleModal=()=>{
setOpenModal(!openModal);
}
返回(
{!OpenModel?
开放模态
:
}
)
}
函数模态({handler}){
返回(
我是情态动词
闭合模态
)
}
ReactDOM.render(,document.getElementById('App'));
在下次渲染之前,您不会看到新状态。另外,我没有看到useffect
call?@pilchard new要做出反应,你能解释一下吗,我的理解是道具更改会重新渲染组件。@pilchard modified OP。。。。。。。。。。。。。。。。。
// if openModal is false render the button, else render our modal
{!openModal ?
<button type="button" onClick={toggleModal}>Open Modal</button>
: <Modal handler={toggleModal} />
}
function Modal({handler}) {
return (
<div className="modal" >
<p>I'm a modal</p>
<button type="button" onClick={handler}>Close Modal</button>
</div>
)
}