从类转换为函数



我正在做一个项目,它的大部分组件都是类,但我需要使用Hooks,所以我需要驾驭类并将它们转换为功能组件,我知道如何做的基本知识,但我卡住了状态和道具这是其中一个类:

import React, { Component } from "react";
import { useHistory } from "react-router-dom";
class Description extends Component {
render() {
const handleSubmit = () => {
this.props.completeTask(this.props.selectedTask, this.state);
};
const history = useHistory();
return (
<>
<p>Completer donnees incident</p>
<label for="description">Description:</label>
<input
type="text"
id="description"
name="description"
onChange={(e) => this.setState({ emetteur: e.target.value })}
/>
<br />
<form action="/">
<button type="button" className="btn btn-primary" onClick={handleSubmit}>
Complete
</button>
<button
type="button"
className="btn btn-primary"
onClick={history.goBack()}
>
Back
</button>
</form>
</>
);
}
}
export default Description;

如何在函数中使用

const handleSubmit = () => {
this.props.completeTask(this.props.selectedTask, this.state);

可以在函数组件中解构props。添加useState来处理本地状态

const Description = ({ selectedTask, completeTask }) => {
const [state, setState] = useState({}); // local state
const handleSubmit = () => {
completeTask(selectedTask, state);
};
return (
<>
<p>Completer donnees incident</p>
<label for="description">Description:</label>
<input
type="text"
id="description"
name="description"
onChange={(e) => {
setState({
emetteur: e.target.value
});
}}
/>
<br />
<form action="/">
<button
type="button"
className="btn btn-primary"
onClick={handleSubmit}
>
Complete
</button>
<button
type="button"
className="btn btn-primary"
onClick={history.goBack()}
>
Back
</button>
</form>
</>
);
};

最新更新