![](/img/trans.png)
[英]How to seperate keys and values from a json and store it in a array using useState hook in react
[英]Add the values from input and store them in an array on a button click using useState hook
我想创建一个这样的精确组件,但使用 react useState 钩子,但我很困惑,因为我是 react-hooks 的新手,请帮帮我
import React, { Component } from "react";
export default class Input2 extends Component {
state = {
cart: []
};
saveInput = (e) => {
this.setState({ input: e.target.value });
};
addNewItem = () => {
this.setState((prevState, props) => ({
cart: [...prevState.cart, prevState.input],
}));
};
render() {
return (
<div>
<input
type="text"
onChange={this.saveInput}
/>
<button onClick={this.addNewItem}> Add Item </button>
<ol>
{this.state.cart.map((Items, Index) => {
return <li key={Index}> {Items}</li>
})}
</ol>
</div>
);
}
}
您可以将 state 换成两个挂钩:
const Input2 = props => {
const [cart, setCart] = React.useState([]);
const [input, setInput] = React.useState([]);
saveInput = e => {
setInput(e.target.value);
};
addNewItem = () => {
setCart(prevState => [...prevState, input]);
};
return (
<div>
<input type="text" onChange={saveInput} />
<button onClick={addNewItem}> Add Item </button>
<ol>
{cart.map((Items, Index) => (
<li key={Index}> {Items}</li>
))}
</ol>
</div>
);
};
export default Input2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.