onclick判断组件调用_从子组件Onclick更新状态

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:

首先在handleSubmitsetState应该是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判断组件调用

你可能感兴趣的:(java,python,vue,javascript,react)