您好我正在尝试将状态从表单传递到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...时,谁能明白为什么?
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>
);
};