[英]Can I setState in Parent from Child component?
我想稍微清理一下我的代碼,所以我不想擁有一個長組件,而是想創建子組件。
在我的Parent
中,我有一些狀態我想更新Child
中的onClick
。
家長:
const [plan, setPlan] = useState('myPlan');
const [months, setMonths] = useState('2');
const [price, setPrice] = useState(200);
<PlanSelection props={props}
item={selectedData}
itemPlan={plan}
/>
孩子
const PlanSelection = ({ props, item, itemPlan }) => {
function handleSubsribe() {
props.setPlan('Subsribe Only');
props.setPrice(item.price);
props.setMonths('24+');
}
function handlePay() {
props.setPlan('Pay to Own');
props.setPrice(item.pay);
props.setMonths('12-24');
}
並嘗試調用函數(在子組件中)
<button onClick={handleSubscribe} />
<button onClick={handlePay} />
單擊其中一個按鈕后,使用上面的代碼會引發錯誤:
類型錯誤:props.setPlan 不是 function
但是如果我不傳遞 props,setPlan、setPrice,.... 將是未定義的。 有辦法處理嗎?
問題
<PlanSelection props={props}
item={selectedData}
itemPlan={plan}
/>
您沒有將setPlan
傳遞給孩子,您只傳遞了props
,它與props
state
, selectedData
我不確定那是什么,還有plan
,它是state
。 總之,您沒有將有關setState
的任何信息傳遞給子組件
家長
const [plan, setPlan] = useState('myPlan');
<PlanSelection
setPlan={setPlan}
/>
孩子
const PlanSelection = ({ setPlan }) => {
function handleSubsribe() {
setPlan('Subsribe Only');
}
function handlePay() {
setPlan('Pay to Own');
}
在上面的代碼中,我僅使用setPlan
作為示例向您展示了如何從子組件設置狀態,您可以將相同的邏輯應用於setState
。
更新剛剛意識到我犯了一個你應該注意的錯誤。 在你的子組件中你有({ setPlan })
,這被稱為解構,這是你從props
中提取setPlan
,因此在你的子組件中,你不應該訪問props.setPlan
而是setPlan
。 再看看上面的答案
您可以簡單地將您的 setState 函數作為道具傳遞給您的子組件。 一種簡單的方法是:
const [plan, setPlan] = useState('myPlan');
const [months, setMonths] = useState('2');
const [price, setPrice] = useState(200);
<PlanSelection setPlan={setPlan}
item={selectedData}
itemPlan={plan}
/>
在這里,您將能夠從子組件更新計划 state。
如果你想將所有的 setStates 傳遞給孩子,試試這個。
const handlers = {setPlan, setMonths, setPrice}
<PlanSelection handlers={handlers}
item={selectedData}
itemPlan={plan}
/>
const PlanSelection = ({ handlers, item, itemPlan }) => {
您可以將setPlan
用作handlers.setPlan
而不是props.setPlan
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.