【问题标题】:Update parent state based on props and onClick from child in React在 React 中基于 props 和来自子级的 onClick 更新父级状态
【发布时间】:2021-08-03 21:57:05
【问题描述】:

我正在用 React 构建一种购物车。我在子组件中设置了一些道具,然后在父组件中使用它们时将状态传递给它们。我想做几件事,但首先我想在按下按钮时更新项目的数量。我知道如果它全部在父组件中编码会如何工作,但我正在尝试创建一个子组件以使代码更高效并弄清楚组件如何相互交互。
这里可以通过onClick事件来操作child的props,用来改变不同事物的状态吗?
如果是这样,我该怎么做?
有没有一种合乎逻辑的方法来创建它,还是有更简单的方法?
我知道 Redux 使用状态管理,但我现在想在 React 中解决这个问题。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      applesCount: 0,
      orangesCount: 0,
      peachesCount: 0,
      grapesCount: 0,
      applesPrice: 0.00,
      orangesPrice: 0.00,
      peachesPrice: 0.00,
      grapesPrice: 0.00
    }
  }
  
  render() {
    return (
      <>
      <h1 className="text-center">Grocery Store</h1>
      <div className="row text-center m-2">
        <div className="col border border-primary m-2">
          <Item fruitName='Apples' quantity={this.state.applesCount} price={this.state.applesPrice}/>
        </div>
        <div className="col border border-primary m-2">
          <Item fruitName='Oranges' quantity={this.state.orangesCount} price={this.state.orangesPrice}/>
        </div>
        <div className="col border border-primary m-2">
          <Item fruitName='Peaches' quantity={this.state.peachesCount} price={this.state.peachesPrice}/>
        </div>
        <div className="col border border-primary m-2">
          <Item fruitName='Grapes' quantity={this.state.grapesCount} price={this.state.grapesPrice}/>
        </div>
      </div>
      </>
    )
  }
}

class Item extends React.Component {
  render() {
    return (
      <>
      <h1>{this.props.fruitName}</h1>
      <div>picture here</div>
      <div className="row d-flex justify-content-center">
        <button>-</button>
        <h1>{this.props.quantity}</h1>
        <button>+</button>
      </div>
      <h2>${this.props.price}</h2>
      </>
    )
  }
}

export default App;

【问题讨论】:

  • 从问题的外观来看,我认为您想在子项中添加单击事件以更新父项中的状态?
  • @MohibArshi 是的。或者下线,状态中有很多东西,因为我也需要更新价格。

标签: javascript reactjs


【解决方案1】:

将回调传递给孩子。

const Parent = () => {
  const [value, setValue] = useState('')

  return <Child setValue={setValue}/>
}

...

const Child = ({setValue}) => {
  // use setValue here which will update parent state
}

【讨论】:

    【解决方案2】:

    你可以为此做很多类型的解决方案

    1. 将执行 setState 的方法传递给子节点并在其中调用它,然后您可以更新从道具获取的父节点的状态。

      const 父级 = () => { const [value, setValue] = useState('') 返回 (); }

      const Child = ({setValue}) => {}

    2. 用 redux 或其他状态管理库来做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-16
      • 2021-10-29
      • 1970-01-01
      • 2016-09-29
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多