【问题标题】:How to call a change a state in a component using a button function from another component In React?如何使用 React 中另一个组件的按钮功能调用组件中的状态更改?
【发布时间】:2021-07-28 01:36:21
【问题描述】:

长话短说;我有一个涉及函数的按钮,在该函数中,我想从另一个从其他地方获取属性的组件更改状态(在本例中为数字)。

所以对我来说,我制作了一个 stats 组件,它接收我想要更改的值,然后该值来自 Table 组件,我希望我制作的按钮来自 Actions 组件从 stats 组件更改状态。因此,我希望能够从我的操作组件中运行它,而不是在表格组件中使用按钮(如下所示)

附加的代码有点像我想要的那样工作,但它看起来不像我想要的那样(我想从 Actions 列而不是在状态所在的组件内部调用更改状态函数)

const Button = ({ handleClick, action, btnType }) => {
  return (
    <div>
      <button class={btnType} onClick={handleClick}>
        {action}
      </button>
    </div>
  );
};

const Actions = ({ text, value, handleClick }) => {
  return (
    <td>
      <button
        type="button"
        class="btn btn-primary"
        data-toggle="modal"
        id="exampleModal"
      >
        Launch demo modal
      </button>
      <Button btnType="btn btn-secondary" action="Attack" />{" "}
      <Button btnType="btn btn-success" action="Travel" />{" "}
    </td>
  );
};

const Stats = ({ cash }) => {
  return (
    <td>
      <ul>
        <li>
          {" "}
          <span class="green">Cash: </span>
          {cash}
        </li>
        <li>
          <span class="red">HP: </span>100
        </li>
        <li>
          <span class="blue">Energy: </span>100
        </li>
      </ul>
    </td>
  );
};

const Table = () => {
  const [cash, setCash] = useState(300);
  const sellAction = ({}) => {
    setCash(cash - 1);
  };
  return (
    <table>
      <tr>
        <th>Drugs</th>
        <th>Quantity</th>
        <th>Inventory</th>
        <th>Stats</th>
        <th>Actions</th>
      </tr>
      <TableItem />
      <QuantItem />
      <Inventory />
      <Button
        btnType="btn btn-danger"
        handleClick={sellAction}
        action="Sell"
      />{" "}
      <Stats cash={cash} />
      <Actions />
    </table>
  );
};

【问题讨论】:

    标签: javascript reactjs react-hooks components state


    【解决方案1】:

    setCashsellAction 函数作为道具传递给Actions 组件。然后从Actions 组件,将其作为道具传递给Button 组件。与您为 cash 所做的类似。

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 2020-06-30
      • 2021-03-14
      • 2020-06-05
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多