![](/img/trans.png)
[英]Calling a function to change state in parent component from the child component in react
[英]How to call component function from parent component and change it state to render child component in React
我在從父組件傳遞 state 時遇到問題。 我正在嘗試從我的 ChildComponent 調用 onClick 中我的 ParentComponent 中的 function 以在 ParentComponent 中呈現 ChildComponent。 我是 React Library 的新手,我真的不知道如何實現它。 我試過類似的東西。
父組件:
import React from 'react'
import {ChildComponent, showDialog} from './childComponent'
const ParentComponent = () => {
return (
<div>
<button type='button' onClick={() => showDialog()}>
</div>
)
}
export default ParentComponent
子組件:
import {React, useState} from 'react'
const {isOpened, setIsOpened} = useState(false)
function showDialog() {
setIsOpened(true)
}
function ChildComponent() {
if (isOpened) {
return (
<dialog open></dialog>
)
}
}
export {ChildComponent, showDialog}
您應該將激活 function 作為道具傳遞給子組件。 然后在孩子點擊時使用 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.