簡體   English   中英

使用 useState 鈎子更新對象

[英]Updating an object with useState hook

您好,我正在嘗試將狀態從表單傳遞到父組件中的useState鈎子,但是當我提交表單時沒有任何反應。 目的是在用戶輸入高度寬度和顏色時在屏幕上創建一個框的視覺效果。

表格代碼:

const NewBoxForm = (props) => {

    const [height, setHeight] = useState();
    const [width, setWidth] = useState();
    const [color, setColor] = useState("");


    const handleChange = (event) => {
        const {value, name } = event.target;
        let change = name === "height" ? setHeight(value) : name === "width" ? setWidth(value) : 
       setColor(value);
    };
 
     const handleSubmit = (event) => {
        event.preventDefault();
        props.createBox(height, width, color);
     };

    return (
      <form onSubmit={handleSubmit}>
          <div>
              <label htmlFor="height">Height</label>
              <input name="height" id="height"type="text" onChange={handleChange} value= 
              {height}>
              </input>
              <label htmlFor="width">Width</label>

              <input name="width" id="width" type="text"onChange={handleChange} value={width}>
              </input>
              <label htmlFor="color">Color</label>
              <input name="color" id="color"type="text" onChange={handleChange} value={color}>
              </input>
          </div>
            <button>Submit</button>
      </form>
    );
};


我通過 prop props.createBox將輸入從我的表單props.createBox給一個函數create ,該函數應該更新我的useState狀態boxes但它沒有。 當我console.log newBox它只返回height ......有人能明白為什么嗎?

const BoxList = () => {
const [boxes, setBoxes] = useState([{height: 0, width:0, color:""}]);

const boxesArray = boxes.map((box) => {
    return(
    <Box width={box.height}
         height={box.width}
         color={box.color}
    />
    )
});

const create = (newBox) => {
    console.log(newBox)
    setBoxes(boxes => [...boxes, newBox])
};


    return (
        <div>
            <NewBoxForm createBox={create} />
            {boxesArray}
        </div>

    );
};
const create = (height, width, color) => {
    let newBox = {height: height, width: width, color: color};
    console.log(newBox);
    setBoxes(boxes => [...boxes, newBox])
};

您在 handleSubmit 調用中發送了三個單獨的變量,而不是一個對象。

const handleSubmit = (event) => {
    event.preventDefault();
    props.createBox(height, width, color);
 };

應該:

const handleSubmit = (event) => {
    event.preventDefault();
    props.createBox({height, width, color});
 };

console.log 只記錄高度,因為這是您發送的第一個參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM