import React, { useState } from 'react'
import Dialog from './components/Dialog'
export default function App() {
const [show,setShow] = useState(false)
let update =()=>{
setShow(false)
}
return (
<div>
<button onClick={()=>{
setShow(true)
}}>+新增</button>
<Dialog visisable={show} onUpdate={update}>
<p>新增用户</p>
</Dialog>
</div>
)
}
import React, { useEffect, useState } from 'react'
import '../assets/css/dialog.scss'
export default function Dialog(props) {
const {children,visisable,onUpdate} = props
const [show,setShow] = useState(visisable)
const confirm = ()=>{
setShow(false)
onUpdate()
}
useEffect(()=>{
setShow(visisable)
},[visisable])
const cancel = ()=>{
setShow(false)
onUpdate()
}
if(show){
return (
<div className='dialog'>
<div className="dialog-center">
{/* 标题 */}
<p>{children}</p>
<div>内容</div>
<div>
<button onClick={confirm}>确定</button>
<button onClick={cancel}>取消</button>
</div>
</div>
</div>
)
}else{
return null
}
}
注意:
子组件接收到值之后,用useState保存,二次编译后,useState会将第一次编译保存的值作为默认值,所以props值发生变化时,我们需要让useState知道props中的visisable已经发生改变了,所以就需要useEffect来监控props中的值并且调用setState。