封装既可显示文本又可编辑文本的组件

import { EditOutlined } from '@ant-design/icons';
import { Input, InputProps } from 'antd';
import { ChangeEvent, useState } from 'react';
interface EditTextInputProps extends Omit<InputProps, 'value' | 'onChange' | 'onPressEnter'> {
value?: string;
onChange?: (value: string) => void;
onPressEnter?: () => void;
defaultValue?: string;
}
const EditTextInput: React.FC<EditTextInputProps> = ({
value: propsValue,
onChange: propsOnChange,
onPressEnter: propsOnPressEnter,
defaultValue = '',
...restProps
}) => {
const [internalValue, setInternalValue] = useState<string>(
propsValue !== undefined ? propsValue : defaultValue
);
const [showInput, setShowInput] = useState(false);
const handlePressEnter = async () => {
if (propsOnPressEnter) {
await propsOnPressEnter();
}
setShowInput(false);
};
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInternalValue(newValue);
if (propsOnChange) {
propsOnChange(newValue);
}
};
const displayValue = propsValue !== undefined ? propsValue : internalValue;
return (
<>
{!showInput && (
<>
<span title={internalValue}>{internalValue}</span>
<span onClick={() => setShowInput(true)}>
<EditOutlined />
</span>
</>
)}
{showInput && (
<Input
value={displayValue}
onPressEnter={handlePressEnter}
onChange={handleChange}
{...restProps}
/>
)}
</>
);
};
export default EditTextInput;