javascript 从组件数组中获取组件属性

6yt4nkrj  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(132)

我正在处理一个react组件。假设我有这样一个数组:

let data: {title: ReactNode}[] = [
   {title: "test1"}, 
   {title: <Component1 title="test2" />},
   {title: "200"},
   {title: <Component2 title="test3" />}
 ]

我有一个getTitle方法:

let result = {};

const getTitle = () => {

 data.map((item, index) => {
  switch (typeof item.title) {
    case "string":
      result[index] = item.title;
      break;
    case "object":
      result[index] = item.title;
      break;
  }
});

};

对于组件,它返回如下对象:

{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}

然后当我想访问props对象(item.title.props)时,它返回一个错误:

Property 'props' does not exist on type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactFragment | ReactPortal'.
Property 'props' does not exist on type 'ReactFragment'.ts(2339)

是否可以在Reactnode数组中获取组件的属性?

e4yzc0pl

e4yzc0pl1#

由于您的组件可以正常工作,请尝试以下操作

//previous cases...
  case "object":
      result[index] = item.title().props.title;
      break;
  • 编辑 *
//previous cases...
      case "object":
          result[index] = item.title.props.title;
          break;

相关问题