![](/img/trans.png)
[英]How to trigger an event in Parent Component from Child Component onClick() using React Hooks?
[英]How to pass the onClick() event to a child component from a button in the parent component in React?
假設我有兩個組件 Component1 和 Component2。 我在 Component1 中有一個按鈕。
const Component1 = () => {
return(
<div>
<button onClick={()=>someExportFunc()}>Export</button>
<Component2 />
</div>
)
}
我的Component2.jsx
是這樣的。
import {ChartComponent} from '@xyz/charts';
const Component2 = () => {
let chartInstance = new ChartComponent();
return (
<ChartComponent
id='chart1'
ref={chart = chartInstance => chart}
>
</ChartComponent>
)
}
現在函數someExportFunc()
被定義在{ChartComponent}
被導入Component2.jsx
中。
如果我使用 Component2 中的按鈕,它會很簡單。 如中,
import {ChartComponent} from '@xyz/charts'
const Component2 = () => {
let chartInstance = new ChartComponent();
return (
<button onClick={()=>someExportFunc()}>Export</button>
<ChartComponent
id='chart1'
ref={chart = chartInstance => chart}
>
</ChartComponent>
)
}
但是我怎樣才能讓它在 Component1 中作為一個按鈕工作呢?
我猜它與定義按鈕的狀態然后將狀態向下傳遞有關,但我並不完全了解按鈕的狀態是如何工作的。 onClick()
應該是一些瞬時布爾值,不是嗎? 瞬時,我的意思是一旦“點擊”結束,它就會改變。
Edit1 :好的,所以someExportFunc()
是我的導入中定義的庫函數。 它利用了在 Component2 中創建的chartInstance
。 它的實際用例是
<button
value='export'
onClick={() => chartInstance.exportModule.export('PNG',
`image`)}>
Export
</button>
所以基本上我想要它,這樣當我單擊 Component1 中的按鈕時,它會將 onClick 事件發送到 Component2 中的 ChartComponent。
React 使用單向數據綁定,在這種情況下意味着父到子。
如果組件 2 是組件 1 的子組件,則在組件 1 中定義函數,並將函數和圖表組件分別作為 props 和 children 傳遞。
家長:
const Component1 = () => {
const someFunc = () => {...}
return <Component2 someFunc={someFunc}> <ChartComponent/> </Component2>
}
孩子:
const Component2 = (props) => {
props.someFunc();
return <div> {props.children} </div>
}
我們需要將該函數作為道具傳遞給第二個組件。
第一個組件
<SecondComponent { ...data } onClick={ () => manageClick() } />
在第二個組件中,點擊時使用 onClick 道具。
第二組件
<button onClick={onClick}>Click</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.