reactjs - React dinamik eleman anahtarı ve değeri ekle


Butona dinamik bir olay anahtarı eklemeye çalışıyorum.

interface ButtonProps{
    actionType: string,
    actionCb: any
}

const Button = (props: ButtonProps)=>{
  return (
    <button {props.actionType}={props.actionCB}>
      Click me
    </button>
  )
}

Böyle bir şey yapmak mümkün mü? Yoksa bunun için başka bir çözüm yolu var mı? Teşekkürler!

Cevap #1

Geçersiz actionType göndermemek için, string kullanmak yerine doğru türü kullanmanız gerekir ve dinamik öznitelikleri kullanmak için yayma operatörünü kullanın

interface ButtonProps {
  actionType: keyof React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>
  actionCb: any
}

const Button = (props: ButtonProps) => {
  return (
    <button {...{ [props.actionType]: props.actionCb }}>Click Me</button>
  )
}

Cevap #2

Öznitelikleri dinamik olarak elemana uygulamak için prop'ları anahtar-değer nesnesi olarak geçir ve spread operatörünü kullan

interface ButtonAttributes{
    actionType: string, 
}

interface ButtonProps{
    [ButtonAttributes.actionType]: actionCb, // like "title": "value"
}

 <button {...props}>
      Click me
    </button>