Valid Input Methods: A Guide to Conditional Rendering Controls
P粉550257856
P粉550257856 2023-08-15 18:18:12
0
2
408

I'm trying to enter conditional rendering, but it gives me the error: Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types'. No index signature with a parameter of type 'number' was found on type 'types'. Rendering is valid when everything is "any".

interface types { '0': JSX.Element; '1': JSX.Element; '2': JSX.Element; } export default function Economy(props: any) { const [step, setStep] = useState(0) const render = () => { const component: types = { '0': , '1': , '2': , } return component[step] } return ( {render()} )

Can anyone help me understand how to add types for this conditional rendering?

I need to understand how to add types for this conditional rendering

P粉550257856
P粉550257856

reply all (2)
P粉823268006

When indexing an object, you need to use thekeyofoperator. From the TypeScript documentation:

interface types { '0': JSX.Element; '1': JSX.Element; '2': JSX.Element; } export default function Economy(props: any) { const [step, setStep] = useState("0") const render = () => { const component: types = { '0': , '1': , '2': , } return component[step] } return ( {render()} )
    P粉008829791

    Yourstephas typenumberand cannot be used to indextypesbecausetypesonly has1,2, 3. So you can manually setsteptokeyof types:

    const [step, setStep] = useState(0)

    Sincestepis a number, you also need the key:

    interface types { 0: JSX.Element; 1: JSX.Element; 2: JSX.Element; } const component: types = { 0: , 1: , 2: , } return component[step] // 没有错误
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!