代码之家  ›  专栏  ›  技术社区  ›  Hiba Youssef

类型“{title _part_1:string;title _part_2:string!}”不可分配给类型“string”

  •  0
  • Hiba Youssef  · 技术社区  · 3 年前

    我有一个组件( StepperTile )接受以下道具:

    title_part_1
    
    title_part_2
    

    但是,当我尝试渲染组件时,我在的文件中收到了此错误 阶梯文件 :

    未捕获的错误:对象作为React子对象无效(找到:具有键{}的对象)。如果要渲染子对象的集合,请改用数组。

    以及渲染组件的文件中的此错误 阶梯文件 小时候:

    类型“{title _part_1:string;title _part_2:string!}”不可分配给类型“string”

    这是我的组件的定义:

    import { Center, VStack, Text, Box } from '@chakra-ui/react';
    import React from 'react';
    
    const StepperTitle = (title_part_1: string, title_part_2: string) => {
        return (
            <>
                <Box>
                    <VStack>
                        <Text
                            fontWeight='700'
                            fontSize={['18px', '23px', '23px', '25px', '28px']}
                            lineHeight='34px'
                            color='#434E61'
    
                        >
                            {title_part_1}
                        </Text>
    
                        <Center>
                            <Text
                                fontWeight='700'
                                fontSize={['18px', '23px', '23px', '25px', '28px']}
                                lineHeight='34px'
                                color='#434E61'
                            >
                                {title_part_2}
                            </Text>
                        </Center>
                    </VStack>
                </Box>
            </>
        )
    }
    
    export default StepperTitle;
    

    以下是我渲染组件的方式:

    <StepperTitle title_part_1=' Tell us what you’re' title_part_2='interested in' />
    
    1 回复  |  直到 3 年前
        1
  •  3
  •   Henry Woody    3 年前

    在React中,道具是作为对象传递的,而不是作为单独的参数传递的。阅读 docs on Components and Props 详细信息。

    你需要重新定义你的 <StepperTitle> 组件来反映这一点,以便它接受一个参数,该参数是您所需类型的道具对象,因此更改:

    const StepperTitle = (title_part_1: string, title_part_2: string) => {
    

    const StepperTitle = ({ title_part_1, title_part_2 }: { title_part_1: string, title_part_2: string }) => {
    

    现在发生的事情是React将整个props对象传递到第一个参数中( title_part_1 ),它应该是一个字符串,这就是为什么会出现类型错误的原因。