使用useState挂钩更新对象

时间:2020-09-07 07:56:14

标签: javascript reactjs forms

您好,我试图将状态从表单传递到父组件中的const Demo = () => { const onFinish = (values) => { console.log("Success:", values); //Can directly call props here }; const onFinishFailed = (errorInfo) => { console.log("Failed:", errorInfo); }; return ( <Form {...layout} name="basic" initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} > <Form.Item label="Title" name="title"> <Input name="title" placeholder="Enter a Title" /> </Form.Item> <Form.Item label="Content" name="content"> <Input name="content" placeholder="Enter the content of the announcement here" /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> ); }; 钩子,但是提交表单时什么也没有发生。目的是当用户输入高度宽度和颜色时在屏幕上创建一个盒子的视觉效果。

表单代码:

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> ); }; 传递给函数props.createBox,该函数应该更新create状态useState,但不会。当我boxes console.log时,它仅返回newBox ...有人可以看到原因吗?

height

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您将在handleSubmit调用中发送三个单独的变量,而不是一个对象。

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

应为:

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

console.log仅记录高度,因为这是您要发送的第一个参数。