onclick判斷組件調用
How to update the state of a parent component from a child component is one of the most commonly asked React questions.
如何從子組件更新父組件的狀態是最常見的React問題之一。
Imagine you're trying to write a simple recipe box application, and this is your code so far:
想象一下,您正在嘗試編寫一個簡單的配方盒應用程序,到目前為止,這是您的代碼:
Eventually you want handleChange
to capture what the user enters and update specific recipes.
最終,您希望handleChange
捕獲用戶輸入的內容并更新特定配方。
But when you try to run your app, you see a lot of errors in the terminal and dev console. Let's take a closer look at what's going on.
但是,當您嘗試運行您的應用程序時,您會在終端和開發控制臺中看到很多錯誤。 讓我們仔細看看發生了什么。
修正錯誤 (Fixing errors)
First in handleSubmit
, setState
should be this.setState
:
首先在handleSubmit
, setState
應該是this.setState
:
handleSubmit() {const newRecipe = this.state.recipelist[0].recipe;this.setState({recipeList[0].recipe: newRecipe});
}
You're already prop drilling, or passing things from the parent RecipeBox
component to its child EditList
properly. But when someone enters text into the input box and clicks "Submit", the state isn't updated the way you expect.
您已經RecipeBox
鉆探,或將其從父RecipeBox
組件正確傳遞到其子EditList
。 但是,當有人在輸入框中輸入文本并單擊“提交”時,狀態不會按照您期望的方式更新。
如何從子組件更新狀態 (How to update the state from a child component)
Here you're running into issues because you're trying to update the state of a nested array (recipeList[0].recipe: newRecipe
). That won't work in React.
在這里您會遇到問題,因為您正在嘗試更新嵌套數組的狀態( recipeList[0].recipe: newRecipe
)。 那在React中行不通。
Instead, you need to create a copy of the full recipeList
array, modify the value of recipe
for the element you want to update in the copied array, and assign the modified array back to this.state.recipeList
.
相反,您需要創建完整recipeList
數組的副本,為要在復制的數組中更新的元素修改recipe
的值,然后將修改后的數組分配回this.state.recipeList
。
First, use the spread syntax to create a copy of this.state.recipeList
:
首先,使用傳播語法創建this.state.recipeList
的副本:
handleSubmit() {const recipeList = [...this.state.recipeList];this.setState({recipeList[0].recipe: newRecipe});
}
Then update the recipe for the element you want to update. Let's do the first element as a proof of concept:
然后更新要更新的元素的配方。 讓我們做第一個元素作為概念證明:
handleSubmit() {const recipeList = [...this.state.recipeList];recipeList[0].recipe = this.state.input;this.setState({recipeList[0].recipe: newRecipe});
}
Finally, update the current recipeList
with your new copy. Also, set input
to an empty string so the textbox is empty after users click "Submit":
最后,用您的新副本更新當前的recipeList
。 另外,將input
設置為空字符串,以便用戶單擊“提交”后文本框為空:
handleSubmit() {const recipeList = [...this.state.recipeList];recipeList[0].recipe = this.state.input;this.setState({recipeList,input: ""});
}
翻譯自: https://www.freecodecamp.org/news/updating-state-from-child-component-onclick/
onclick判斷組件調用