Javascript 从类到函数的转换
我在做一个项目,它的大部分组件都是类,但我需要使用钩子,所以我需要了解类并将它们转换为功能组件, 我知道如何做的基本知识,但我被状态和道具卡住了 这是其中一个类别:Javascript 从类到函数的转换,javascript,reactjs,react-component,Javascript,Reactjs,React Component,我在做一个项目,它的大部分组件都是类,但我需要使用钩子,所以我需要了解类并将它们转换为功能组件, 我知道如何做的基本知识,但我被状态和道具卡住了 这是其中一个类别: import React, { Component } from "react"; import { useHistory } from "react-router-dom"; class Description extends Component { render() { const
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;
您可以在function component中解构道具。添加
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>
</>
);
};
const Description=({selectedTask,completeTask})=>{
const[state,setState]=useState({});//本地状态
常量handleSubmit=()=>{
完成任务(选择任务,状态);
};
返回(
完成者唐尼事件
说明:
{
设定状态({
目标值
});
}}
/>
完成
返回
);
};
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>
</>
);
};