如何将React类组件转换为函数组件?含动态新增输入框场景
类组件转函数组件完整实现
修复输入框基础组件 inputbox.js
原组件未透传value和onChange属性,无法和父组件状态联动,调整后代码如下:
import React from 'react'; const InputBox = ({ value, onChange }) => { return( <input type="text" placeholder='Add your content line here ... ' value={value} onChange={onChange} /> ); }; export default InputBox;
转换后的函数组件 CreateRecursiveInputBox.js
使用useState Hook替代类组件的内部状态管理,无需额外绑定this上下文:
import React, { useState } from "react"; import styled from "@emotion/styled"; import InputBox from "./inputbox.js"; const Bundle = styled.div` display: flex; flex-direction: row; justify-content: flex-start; gap: 8px; align-items: center; margin: 4px 0; `; const CreateRecursiveInputBox = () => { // 初始化状态,和原类组件state结构一致 const [values, setValues] = useState({ 0: '' }); // 输入内容变更处理 const handleChange = (index, value) => { setValues(prev => ({ ...prev, [index]: value })); }; // 提交新增输入框处理 const handleSubmit = (event) => { event.preventDefault(); const currentLength = Object.keys(values).length; setValues(prev => ({ ...prev, [currentLength]: '' })); }; return ( <div> <form onSubmit={handleSubmit}> {Object.keys(values).map(index => { const value = values[index]; return ( <div key={index}> <Bundle> <label>Name</label> <InputBox value={value} onChange={(event) => handleChange(index, event.target.value)} /> <input type="submit" value="Submit"/> </Bundle> </div> ); })} </form> </div> ); }; export default CreateRecursiveInputBox;
入口组件 App.js
无需调整,保持原有代码即可正常运行。如果也需要转成函数组件可以替换为以下代码:
import React from 'react'; import CreateRecursiveInputBox from './component/CreateRecursiveInputBox.js'; const App = () => { return( <div> <CreateRecursiveInputBox/> </div> ) } export default App;
内容的提问来源于stack exchange,提问作者everestial
相关产品推荐
相关产品推荐

