【问题标题】:Updating Parent State with Child component使用子组件更新父状态
【发布时间】:2021-04-10 19:40:54
【问题描述】:

我正在开发我的第一个 React 项目,作为 CC 上的简单支出跟踪器。我的描述可能很松散,因为我仍在学习,但希望你能通过我的代码看到我正在尝试做的事情。我坚持映射我的状态并给出索引,但通过状态的每个数组值包括输入日期和按钮。

class App extends Component {
  state = {
    cards: [
      { id: 'asfa1', name: 'Capital One', balance: 28 },
      { id: 'vasdf1', name: 'Barclays', balance: 29 },
      { id: 'asdf11', name: 'Discover', balance: 26 }
    ],
    totalDue: null
    
  }
theTotal = () => {
    let total = 0;
    let cardOne = this.state.cards[0].balance
    let cardTwo = this.state.cards[1].balance
    let cardThree = this.state.cards[2].balance
   total = cardOne + cardTwo + cardThree
   console.log('made it')
    this.setState( { totalDue : total } )
}
updateBalance = (cardIndex) => {
  let cards = [...this.state.cards]
  console.log('The card index is = ' + cardIndex)
  let oldBalance = cards[cardIndex].balance
  console.log(oldBalance)
  const addedBalance = document.getElementById('balanceInput').value;
  
  const newBalance = oldBalance + parseInt(addedBalance)
  cards[cardIndex].balance = newBalance
  this.setState( {cards : cards})


 }
  
  render () {

    let card = (
      <div> 
        {this.state.cards.map( ( cards , index) => {
          return ( 
          <Cards 
          name={cards.name}
          balance={cards.balance}
          update={() => this.updateBalance(index)} 
          />
          )
        })}
      </div>
    )

这就是父类的样子。我认为还值得一提的是,我将把它附加到 Firebase 表并让它提交更新。我最初的计划是仅在用户点击并更新按钮后才更新数据库,并且将发布状态更改。但我也考虑过将 POST 处理程序内置到卡片的每个唯一更新中。子组件请看下面的代码。

import React from 'react'
import classes from './Cards.css'
import Input from '../Components/Input'

const cards = (props) => {


return (

    <div className={classes.Cards}>
        <p>{props.name}</p>
        <p>{props.balance}</p>
        {props.children}
        <Input type="text" name="amount" />
        <p></p><button onClick={props.update}>Update Balance</button>
    </div>


)}

export default cards;

我的问题是第一张卡可以工作并更新。但是,当您单击 为第二张卡输入值时,它会使用您在第一张卡上输入的第一个值。如果您从第二张卡开始,则会引发错误和崩溃。

有没有更好的方法来处理孩子的输入?

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    App.js

    
    import './App.css';
    import React, {Component} from 'react'
    import Cards from './Cards'
    
    class App extends Component {
      state = {
        cards: [
          { id: 'asfa1', name: 'Capital One', balance: 28 },
          { id: 'vasdf1', name: 'Barclays', balance: 29 },
          { id: 'asdf11', name: 'Discover', balance: 26 }
        ],
        totalDue: null
    
      }
    theTotal = () => {
    
        let total = 0;
        this.state.cards.forEach(card => {
          total += card.balance; // looping through each card and adding balance to total
        });
    
        console.log('made it')
        this.setState( { totalDue : total } )
    }
    updateBalance = (cardIndex, e) => {
    
      e.preventDefault();
      const {cards} = this.state;
      console.log('The card index is = ' + cardIndex);
    
      let oldBalance = cards[cardIndex].balance;
      console.log(oldBalance);
      const addedBalance = e.target[0].value; // target 0 is the input element
    
      const newBalance = oldBalance + parseInt(addedBalance);
      cards[cardIndex].balance = newBalance;
      this.setState( {cards : cards});
    
    
    
     }
    
      render () {
        return <div>
          {this.state.cards.map( ( cards , index) => {
            return (
            <Cards
            key={index}
            name={cards.name}
            balance={cards.balance}
            index={index}
            update={this.updateBalance}
            />
            )
          })}
        </div>
      }
    
    }
    
    export default App;
    
    

    卡片.js

    import React from 'react'
    
    const cards = (props) => {
    
    
    return (
    
        <div>
            <p>{props.name}</p>
            <p>{props.balance}</p>
            {props.children}
            <form onSubmit={(e) => props.update(props.index, e)}>
              <input type="text" name="amount" />
              <p></p><button>Update Balance</button>
            </form>
        </div>
    
    
    )}
    
    export default cards;
    
    

    沙盒:https://codesandbox.io/s/determined-violet-wo05g?file=/src/App.js

    【讨论】:

    • 我想说谢谢你编码!当我试图消化你写的东西时,我在你的代码中陷入了“e”的概念。有什么方法可以概括地解释“onSubmit={(e) => props.update(props.index, e)”背后的逻辑。我了解 props.index 但不了解 e 所扮演的角色。再次感谢您!
    • e 指的是表单事件。我将它传递给父级以获取该表单的输入值。在卡片的每次迭代中,每张卡片都将在一个表单中,当表单提交时,该表单的事件被捕获,然后通过 e.target[0].value 获取该表单中的值。其中 target[0] 是输入元素。
    • 或者您可以尝试另一种解决方案,方法是制作 Cards Stateful Component 并将 onChange 事件添加到带有状态变量的输入字段。看到这个codesandbox.io/s/thirsty-drake-b9jes?file=/src/Cards.js
    • 这很有意义!我确实有另一个后续问题。您提供的代码不接受十进制输入。它正在做某种类型的舍入。有没有简单的解决方法?
    • 你可以在 addedBalance 上使用 parseFloat 而不是 parseInt
    【解决方案2】:

    在 react 中,用子组件更新父组件的状态是这样的。

    1. 将该方法作为道具传递给子组件。
    2. 在子组件中,使用所需的值调用此方法。
    3. 在父级内部,使用setState 实现方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 2021-08-23
      • 2021-04-06
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2018-10-09
      • 2020-09-22
      相关资源
      最近更新 更多