繁体   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