You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TS报错:Interface已定义属性Y,FunctionComponent<Interface>上不存在该属性如何解决

问题原因
  • 你对wrapper.props.children的类型定义错误:React.FunctionComponent<BlockProps>是Block组件函数本身的类型,而wrapper.props.children是Block组件渲染生成的React元素实例,对应类型是React.ReactElement<BlockProps>
  • blockClassName是你传给Block组件的props属性,不属于组件函数本身的属性,必须从React元素实例的props字段下读取
修复方案

步骤1:(可选但推荐)统一管理BlockProps

在Block/index.tsx中定义并导出Block的属性类型,避免重复定义:

// Block/index.tsx
export interface BlockProps {
  blockClassName: string,
  text: string
}

const Block = ({blockClassName, text}: BlockProps) => {
  if(blockClassName.includes("isEmpty")) text = "";
  return (
    <span className={blockClassName}>
      <Content>
        <h1>{text}</h1>
      </Content>
    </span>
  );
}
export default Block;

之后在Grid/index.tsx中导入这个类型使用即可。

步骤2:修改事件回调中的取值逻辑

直接修正类型断言和属性读取路径:

swappable.on("swappable:swapped", () => {
  for(let wrapper of blockWrappers) {
    // 类型断言为Block对应的React元素
    const childBlock = wrapper.props.children as React.ReactElement<BlockProps>;
    // 从props字段读取属性
    if(childBlock.props.blockClassName) {
      // 你的业务逻辑
      console.log(childBlock.props.blockClassName);
    }
  }
  updateClasses();
});

优化建议:增加运行时校验

如果无法保证BlockWrapper的children一定是单个Block元素,可以加React内置的合法性校验,避免运行时报错:

swappable.on("swappable:swapped", () => {
  for(let wrapper of blockWrappers) {
    const child = wrapper.props.children;
    // 先校验是否为合法React元素,同时传入泛型定义props类型
    if(React.isValidElement<BlockProps>(child)) {
      console.log(child.props.blockClassName);
    }
  }
  updateClasses();
});

内容的提问来源于stack exchange,提问作者user15818211

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:06:00