zchfeng / Front-End-note

1 stars 0 forks source link

实现自适应输入框组件 #16

Open zchfeng opened 2 years ago

zchfeng commented 2 years ago

ts:

import React, { useEffect, useRef } from 'react';

interface IProps {
  value: string;
  placeholder?: string;
  className?: string;
  onChange?: (value: string) => void;
  onFocus?: (value: string) => void;
}
export const AutoInput = (props: IProps) => {
  const { placeholder, value, className = '', onChange, onFocus } = props;
  const inputRef = useRef<HTMLElement>();

  useEffect(() => {
    if (value !== (inputRef.current as HTMLElement)?.innerText) {
      inputRef.current.innerText = value;
    }
  }, [value]);

  const onInput = () => {
    if (inputRef.current) {
      onChange && onChange(inputRef.current?.innerText);
    }
  };

  return (
    <div
      ref={inputRef as React.LegacyRef<HTMLDivElement>}
      className={`auto-input`}
      contentEditable={true}
      data-placeholder={placeholder}
      onInput={onInput}
      onFocus={() => onFocus(inputRef.current?.innerText)}
    />
  );
};

export default AutoInput;

css

.auto-input{
  padding: 8px 12px;
  min-height: 36px;
  max-height: 132px;
  outline: 0;
  line-height: 19px;
  word-wrap: break-word;
  overflow-x: hidden;
  overflow-y: auto;
  transition: height 300ms ease-in-out;
  background-color: rgba(09,09,09,.04);
}
zchfeng commented 2 years ago

参考:https://blog.csdn.net/m553366999/article/details/124973293