如何更新App
功能,以便每次按下按钮时将状态中包含的数据推送到数组?
我曾尝试使用类似array.push(this.state)
的方法,但希望能获得一些指导。
我发现了使用类组件而不使用React钩子的示例。是否需要类似useEffect
的内容?
import React, { Component, useState, setState } from 'react';
import { render } from 'react-dom';
const App = () => {
const [value, setValue] = useState('');
const handleChange = event => setValue(event.target.value);
return (
<div>
<label>
Input:
<input type="text" value={value} onChange={handleChange} />
<input type="button" value="Click Me" onClick={?????}/>
</label>
</div>
);
};
render(<App />, document.getElementById('root'));
您需要为数组创建一个引用,以便在更新后保留其内容:
const arrayRef = useRef([]);
然后您创建一个onClick函数:
const onClick = () => {
arrayRef.current.push(value);
}
并通过按钮调用该功能:
<input type="button" value="Click Me" onClick={onClick}/>