v2.5.2
Giriş yap

React input componentini passwordInput componentinde nasıl kullanabilirim?

Anonim
61 defa görüntülendi

Input ve PasswordInput ortak diyebilirim. Bu ikisini ayrı bileşen olarak kodlayacağım. Input bileşeninin tüm özelliklerini, stillerini PasswordInput bileşeninde nasıl kullanabilirim?

Ortak özelliklere sahip bileşenleri nasıl yönetebilirim react tarafında bunun mantıklı yolu nedir?

Cevap yaz
Cevaplar (1)
ebykdrms
16 gün önce

Ortak özellikleri ve stilleri içeren bir yüksek dereceli bileşen (higher-order component - HOC) oluşturabilirsin.
Input ve PasswordInput bileşenlerini bu bileşene sarabilirsin.
Örneğin:

import React from 'react';

interface InputProps {
  value: string;
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  style?: React.CSSProperties;
}

const withInputProps = (WrappedComponent: React.ComponentType<InputProps>) => {
  const InputWrapper = forwardRef<HTMLInputElement, Omit<InputProps, 'ref'>>((props, ref) => {
    const { forwardedRef, ...otherProps } = props;
    return <WrappedComponent ref={ref} {...otherProps} />;
  });

  return forwardRef<HTMLInputElement, Omit<InputProps, 'ref'>>((props, ref) => {
    return <InputWrapper {...props} forwardedRef={ref} />;
  });
};

export default withInputProps;

Daha sonra Input ve PasswordInput bileşenlerini bu HOC ile sarabilirsin:

import React from 'react';
import withInputProps from './withInputProps';
import BaseInput from './BaseInput';

const Input = withInputProps(BaseInput);
const PasswordInput = withInputProps(BaseInput);

export default { Input, PasswordInput };

Bu yanıtı https://cohere.com yapay zekasından yardım alarak yazım.