React 渲染组件点击按钮

问题描述 投票:0回答:1

如何在 React 中单击按钮时调用/渲染组件?我正在使用“表单”创建一个表并将行称为单独的组件。我希望用户能够在需要时单击按钮向表中添加更多行。我添加了一个带有“onClick”的按钮来调用该行,但没有任何反应。

到目前为止,这是“估计”组件中的部分代码:

import React, { useState } from "react";
import EstimateRow from "./EstimateRow";


const Estimate = () => {
    return(
<div className="estimate-column-names">
                <h3>Category</h3>
                <h3>Subcategory</h3>
                <h3>Item Name</h3>
                <h3>Quanitity</h3>
                <h3>Unit of Measure</h3>
                <h3>Unit Cost</h3>
                <h3>Base Cost</h3>
                <h3>Markup %</h3>
                <h3>Profit Amt</h3>
                <h3>Profit Margin</h3>
                <h3>Total Cost</h3>
            </div>
            <EstimateRow />
            <EstimateRow />
            <EstimateRow />
            <EstimateRow />
            <button 
            className="button"
                      onClick={(e) => {
                          <EstimateRow />;
                      }}
                      >
                        Add Row
                        </button>
            <button type="Submit">Delete Row</button>
)}

EstimateRow 组件只是为每个列标题提供一系列输入。单击按钮后,我希望再次呈现 EstimateRow 并向表中添加更多行。但是没有任何反应。我尝试将其作为异步函数调用/导入并将结果附加到 useState 但这也不起作用。

reactjs button components react-button
1个回答
0
投票
点击按钮时反应渲染组件

我们应该考虑像操作dom一样使用状态来控制dom elem,状态可以控制。

[这是一个例子](https://codesandbox.io/s/flamboyant-james-wygdwx

import React, { useCallback, useState } from "react";
import { EstimateRow } from "./EstimateRow";

const Estimate = () => {
  const [rows, setRows] = useState([]);
  const handleDelete = useCallback(
    (param) => {
      if (rows.length === 0) {
        alert("add rows before you delete");
      }
      const items = rows.filter((item) => item !== param);
      setRows(items);
    },
    [rows]
  );
  return (
    <>
      <div className="estimate-column-names">
        <h3>Category</h3>
        <h3>Subcategory</h3>
        <h3>Item Name</h3>
        <h3>Quanitity</h3>
        <h3>Unit of Measure</h3>
        <h3>Unit Cost</h3>
        <h3>Base Cost</h3>
        <h3>Markup %</h3>
        <h3>Profit Amt</h3>
        <h3>Profit Margin</h3>
        <h3>Total Cost</h3>
      </div>
      <div>
        {rows.map((row) => (
          <EstimateRow row={row} />
        ))}
      </div>
      <button
        className="button"
        onClick={() => setRows([...rows, rows.length + 1])}
      >
        Add Row
      </button>
      <button onClick={() => handleDelete(rows.length)}>Delete Row</button>
    </>
  );
};
export default Estimate;


  • 行组件
export const EstimateRow = ({row}) =>(
  <div>
  row Component {row}
  </div>
)
© www.soinside.com 2019 - 2024. All rights reserved.