reactjs - 如何修复类型错误Type '(string | Element) [] is not assignable to type ' string |元素 |未定义'使用 react 和 typescript ?

标签 reactjs typescript

我想在标签之前添加一些边距,我试图这样做,但出现错误 类型 '(string | Element) [] 不可分配给类型 'string |元素 |未定义'

下面是我的代码,

type CheckboxProps = {
    label?: string;
}

const CheckboxComponent: React.FC<CheckboxProps> = ({
    label,
}) => {
    return (
        <>
            <input type="checkbox" />
            <Label>{label}</Label> 
        </>
    );
}


const ParentComponent = (data) => {
    const name = data.name;
    const type = data.type;
    const label = `${name} ${type}`;
    
    return (
        <Checkbox
            label = {label}
        />
        //some other logic
    );
}

现在的问题是我想在复选框和标签之间添加一些边距。正如您从上面的代码中看到的那样,标签在复选框组件中呈现,我不想修改复选框组件中标签的边距作为其可重用组件。

所以我尝试了下面的解决方案,尝试在 ParentComponent 中为标签添加边距,并将 CheckboxProps 类型中的标签类型更改为接受字符串或元素。

type CheckboxProps = {
    label?: string | Element;
}

const ParentComponent = (data) => {
    const name = data.name;
    const type = data.type;
    const label = [<span style={{marginLeft: '4px'}}>${name}</span>, `${type}`];
    
    return (
        <Checkbox
            label = {label}
        />
        //some other logic
    );
}

但是上面的代码抛出错误 Type '(string | Element) [] is not assignable to type 'string |元素 |未定义'

注意: 复选框组件是可重用组件,它接受来自其他组件的标签作为字符串。只有 ParentComponent 像上面的代码一样发送标签。

有人可以帮我解决这个问题吗?如何修复类型错误或任何更好的解决方案来增加 margin 。我是编程新手。谢谢。

最佳答案

CheckboxProps 中的 label 类型转换为 HTMLElement。所以试试这个复选框:

type CheckboxProps = {
    label?: HTMLElement;
}

const CheckboxComponent: React.FC<CheckboxProps> = ({
    label,
}) => {
    return (
        <>
            <input type="checkbox" />
            {label && (<Label>{label}</Label>)}
        </>
    );
}

这是父组件:

const ParentComponent = (data) => {
    const name = data.name;
    const type = data.type;
    const label = <span style={{marginLeft: '4px'}}>${name} ${type}</span>;
    
    return (
        <Checkbox
            label = {label}
        />
        //some other logic
    );
}

关于reactjs - 如何修复类型错误Type '(string | Element) [] is not assignable to type ' string |元素 |未定义'使用 react 和 typescript ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68843301/

相关文章:

javascript - 带 Prop 的 Jest 快照

javascript - 如何在 React 中动态改变状态?

reactjs - creactAsyncThunk 中的 action.payload 未定义

typescript - Typeguard 不会缩小类型

javascript - typescript中的类有什么用

javascript - ReferenceError 因为变量没有被传递

javascript - React.addons.batchedUpdates API 的用途是什么?

typescript - 是否可以使用 webpack 加载程序从文件生成 Typescript 接口(interface)?

reactjs - 如何在 react typescript 中将 ref 添加到 CSVLINK?

javascript - typescript : Unexpected token; 'constructor, function, accessor or variable'