javascript 如何将onChange事件添加到react中使用www.example.com()呈现的输入字段array.map?

3lxsmp7m  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(102)

我正在做一些其他的事情,但是下面的代码片段和我面临的问题很相似。在下面的代码中,输入字段是动态生成的。
我想处理inputonChange事件,所以我像往常一样,取了一个状态变量,用它来处理输入状态,当然,它不起作用,如果我更改一个输入字段,其他字段也会受到影响,现在很明显为什么会发生这种情况。

import { useState } from "react";
export default function App() {
  let [arr, setArr] = useState(["a", "b", "c", "d"]);
  const [input, setInput] = useState(0);
  return (
    <div className="App">
      {arr.map((item, idx) => {
        return (
          <div key={idx}>
            <p>{item}</p>
            <input
              placeholder="enter value"
              type="number"
              value={input}
              onChange={(e) => setInput(e.target.value)}
            />
          </div>
        );
      })}
    </div>
  );
}

编辑:这是最初的问题。

股票.jsx

我有一个quantity状态变量,用来管理输入元素的状态,但是,当有多个输入元素时,它就不起作用了,它产生的问题是,任何输入域的改变也会改变其他输入域。

import {
  Box,
  Button,
  Grid,
  GridItem,
  Heading,
  Image,
  Input,
  Text,
} from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { getStock } from "../redux/appReducer/action";
import { useDispatch } from "react-redux";

export const Stocks = () => {
  const dispatch = useDispatch();
  const stocks = useSelector((store) => store.AppReducer.stocks);

/* 
  Format of the data coming in the stocks

[
    {
        "id" : 1,
    "company_logo": "https://logolook.net/wp-content/uploads/2021/11/HDFC-Bank-Logo.png",
    "company_name": "HDFC Bank",
    "company_type": "Bank",
        "stock_exchange": "NSE",
        "total_shares": 50000,
        "cost_per_share": 4210,
        "price_action": 12,
  },
  {
        "id" : 2,
    "company_logo": "https://www.jetspot.in/wp-content/uploads/2018/03/reliance-logo.jpg",
    "company_name": "Reliance Industries",
    "company_type": "Oil",
        "stock_exchange": "BSE",
        "total_shares": 20000,
        "cost_per_share": 2132,
        "price_action": 4,
  }
]
  
*/
  const [quantity, setQuantity] = useState(0);

  useEffect(() => {
    dispatch(getStock());
  }, []);

  return (
    <Grid
      templateColumns="repeat(2, 350px)"
      templateRows="repeat(2, auto)"
      justifyContent="center"
      alignItems="center"
      gap="20px"
      pt="30px"
      pb="30px"
    >
      {stocks?.map((stock, index) => {
        return (
          <GridItem
            boxShadow="rgba(3, 102, 214, 0.3) 0px 0px 0px 3px"
            justifyContent="center"
            p="20px"
            key={stock.id}
          >
            <Box mb="10px">
              <Image h="80px" src={stock?.company_logo} />
            </Box>
            <Box mb="10px">
              <Heading size="md">{stock?.company_name}</Heading>
            </Box>
            <Box mb="10px">
              <Text as="span">EXCHANGE: </Text>
              <Text as="span">{(stock?.stock_exchange).toUpperCase()}</Text>
            </Box>
            <Box mb="10px">
              <Text as="span">TYPE: </Text>
              <Text as="span">{(stock?.company_type).toUpperCase()}</Text>
            </Box>
            <Box mb="10px">
              <Text as="span">TOTAL SHARES: </Text>
              <Text as="span">{stock?.total_shares}</Text>
            </Box>
            <Box mb="10px">
              <Text as="span">COST PER SHARE: </Text>
              <Text as="span">{stock?.cost_per_share}</Text>
            </Box>
            <Box mb="10px">
              <Text as="span">PRICE ACTION: </Text>
              <Text as="span">{stock?.price_action}</Text>
            </Box>
            <Box mb="10px">
              <Input
                value={quantity}
                type="number"
                placeholder="Quantity"
                onChange={(e) => setQuantity(e.target.value)}
              />
            </Box>
            <Box mb="10px">
              <Button colorScheme="green">Buy</Button>
            </Box>
          </GridItem>
        );
      })}
    </Grid>
  );
};

行动.js

import * as types from "./actionTypes";
import axios from "axios";
export const getStock = () => (dispatch) => {
  dispatch({ type: types.GET_STOCK_REQUEST });
  return axios
    .get("https://stockbroker.onrender.com/companies")
    .then((res) => {
      //   console.log(res);
      dispatch({ type: types.GET_STOCK_SUCCESS, payload: res.data });
    })
    .catch((e) => dispatch({ type: types.GET_STOCK_FAILURE }));
};

减速器.js

import * as types from "./actionTypes";
const initialState = {
  isLoading: false,
  isError: false,
  stocks: [],
};

export const reducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case types.GET_STOCK_REQUEST:
      return {
        ...state,
        isLoading: true,
      };
    case types.GET_STOCK_SUCCESS:
      return {
        ...state,
        isLoading: false,
        stocks: payload,
      };
    case types.GET_STOCK_FAILURE:
      return {
        ...state,
        isLoading: false,
        isError: true,
        stocks: [],
      };
    default:
      return state;
  }
};
sshcrbum

sshcrbum1#

如果将arr转换为对象是一种选择,那么您可以这样做,并将其用作输入的控制状态:

import React from 'react';
import { useState } from "react";

export  function App() {
   const [obj, setObj] = useState({
    a: 0,
    b: 0,
    c: 0,
    d: 0
  });

  return (
    <div className="App">
      {Object.keys(obj).map((item, idx) => {
        return (
          <div key={idx}>
            <p>{item}</p>
            <input
              placeholder="enter value"
              type="number"
              value={obj[item]}
              onChange={(e) => setObj(prev => ({...prev, [item]: e.target.value}))}
            />
          </div>
        );
      })}
    </div>
  );
}

相关问题