【问题标题】:Passing props within stateless functional components在无状态功能组件中传递道具
【发布时间】:2020-08-19 14:13:45
【问题描述】:

我有一个叫 Productos 的父亲和一个叫 EditarProductos 的孩子。我想将 producto.id 传递给 EditarProductos。

这是产品:

import {Button, TableHead, TableRow, TableCell, TableBody, Table} from '@material-ui/core'
import { withStyles, makeStyles } from '@material-ui/core/styles';
import InsertarProductos from './InsertarProductos';
import Grid from '@material-ui/core/Grid';
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import EditarProductos from './EditarProductos';

const StyledTableCell = withStyles((theme) => ({
  head: {
    backgroundColor: theme.palette.common.black,
    color: theme.palette.common.white,
  },
  body: {
    fontSize: 14,
  },
}))(TableCell);

const StyledTableRow = withStyles((theme) => ({
  root: {
    '&:nth-of-type(odd)': {
      backgroundColor: theme.palette.background.default,
    },
  },
}))(TableRow);

function Productos(props) {
    const [productos, setProductos] = useState([]);
    var id='';

    useEffect(() => {


      const getProductos = async () => {
        const res = await fetch("/productos", {
            method: 'GET',
            headers: {'Content-Type': 'application/json'},
        })
        //console.log(res);
        const response = await res.json();
        setProductos(response);
      }
      getProductos();
    })

    function editar(producto){
      console.log("entro 1");
      //console.log(producto.id);
      id = producto.id;
      console.log(id);
      return <EditarProductos productoEdit = {id}/>;
    }

    function eliminar(producto){
      console.log(producto.id);
      id=producto.id;
      deleteProductos();
      window.location.reload();
    }

    const deleteProductos = async () => {
      console.log("entro");
      console.log(id);
      const res = await fetch("/productos", {
          method: 'DELETE',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            id: id
          })
      })
      const response = await res.json();
    }

    const useStyles = makeStyles({
      table: {
        minWidth: 700,
      },
    });
    //console.log(plot);

    const mystlye = {
      minWidth: "50%",
      minHeight: 50
    };

    //
    const classes = useStyles();
    return (
      <div>

      <br />
        <Grid container spacing={3}>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}>
         <InsertarProductos productoInsert="fer"/>
        </Grid>
      </Grid>
      <br />
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <StyledTableCell>ID</StyledTableCell>
              <StyledTableCell>Nombre</StyledTableCell>
              <StyledTableCell>Precio de Compra</StyledTableCell>
              <StyledTableCell>Precio de Venta</StyledTableCell>
              <StyledTableCell>Cantidad</StyledTableCell>
              <StyledTableCell>Categoria</StyledTableCell>
              <StyledTableCell>Extras</StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {productos.map((producto) =>
              <TableRow className="data-row">
                <StyledTableCell>{producto.id}</StyledTableCell>
                <StyledTableCell>{producto.nombre}</StyledTableCell>
                <StyledTableCell>{producto.precio_compra}</StyledTableCell>
                <StyledTableCell>{producto.precio_venta}</StyledTableCell>
                <StyledTableCell>{producto.cantidad}</StyledTableCell>
                <StyledTableCell>{producto.categorias_id}</StyledTableCell>
                <StyledTableCell> 
                <Button variant="outlined" onClick={() => editar(producto)}>
                  <EditIcon />
                </Button>
                <Button variant="outlined" onClick={() => eliminar(producto)} ><DeleteIcon /> </Button>
                </StyledTableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    );
}

export default Productos;

如果我尝试在按钮内传递 id,它会像循环一样开始多次打印 id。

EditarProductos 永远不会到达,id 也不会传递。有人可以帮我解决我的问题吗?

PD:在 EditarProductos 中,我尝试像这样打印 id:

console.log(props.productoEdit);

【问题讨论】:

  • 当您在 onClick 处理程序中返回 &lt;EditarProductos productoEdit = {id}/&gt; 时,您想用它做什么?
  • 我正在尝试返回一个对话框。

标签: javascript html reactjs react-hooks


【解决方案1】:

您不能像这样返回(和渲染)UI 元素。不过,您可以将产品的 id 设置为显示。使用 is 您可以有条件地将 EditarProductos 渲染到 UI 中。当对话框被关闭/关闭时,您可能还需要/需要一种方法来重置它。

以下是执行此操作的一种方法:

function Productos(props) {
    const [productos, setProductos] = useState([]);
    const [id, setId] = useState(null); // create state variable

    ...

    function editar(producto){
      console.log("entro 1");
      console.log(producto.id);
      setId(producto.id);
    }

    function onEditarClose() {
      setId(null);
    }

    ...

    return (
      <div>
      {id && 
         // conditionally render in UI the dialog
         <EditarProductos onClose={onEditarClose} productoEdit={id} />
      } 
      <br />
        <Grid container spacing={3}>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}></Grid>
        <Grid item xs={3}>
         <InsertarProductos productoInsert="fer"/>
        </Grid>
      </Grid>
      <br />
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <StyledTableCell>ID</StyledTableCell>
              <StyledTableCell>Nombre</StyledTableCell>
              <StyledTableCell>Precio de Compra</StyledTableCell>
              <StyledTableCell>Precio de Venta</StyledTableCell>
              <StyledTableCell>Cantidad</StyledTableCell>
              <StyledTableCell>Categoria</StyledTableCell>
              <StyledTableCell>Extras</StyledTableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {productos.map((producto) =>
              <TableRow className="data-row">
                <StyledTableCell>{producto.id}</StyledTableCell>
                <StyledTableCell>{producto.nombre}</StyledTableCell>
                <StyledTableCell>{producto.precio_compra}</StyledTableCell>
                <StyledTableCell>{producto.precio_venta}</StyledTableCell>
                <StyledTableCell>{producto.cantidad}</StyledTableCell>
                <StyledTableCell>{producto.categorias_id}</StyledTableCell>
                <StyledTableCell> 
                <Button variant="outlined" onClick={() => editar(producto)}>
                  <EditIcon />
                </Button>
                <Button variant="outlined" onClick={() => eliminar(producto)} ><DeleteIcon /> </Button>
                </StyledTableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
    );
}

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    相关资源
    最近更新 更多