我试图将一个项推入存储在属性中的数组中,得到一个错误:无法读取未定义的属性(读取'value')
在我的道具里:
ILinkItemProps.ts
export interface ILinkItemProps {
id:string;
title:string;
action:string;
anchorid:string;
trans:string;
}
export class LinksItem implements ILinkItemProps {
constructor (
public id: string = null,
public title: string = null,
public action: string = null,
public anchorid: string = null,
public trans: string = null) { }
}ILinksProp.ts
import {LinksItem} from './ILinkItemProps';
export interface ILinksProps {
linkItems:Array<LinksItem>;
}在webpart.ts里我有:-
public render(): void {
const element: React.ReactElement<ILinksProps> = React.createElement(
links,
{
linkItems: this.properties.linkItems,
updateEditLink: (index: number) => {
let arr = this.properties.linkItems;
if (arr?.push) {
arr.push(new LinksItem());
} else {
console.log('arr is undefined or null');
}
}
}
)有人知道数组为什么没有定义吗?
发布于 2022-07-28 12:17:24
使用this.props而不是this.properties应该可以让您访问传递给组件的道具。下面是使用this.props重写的示例
import React from 'react';
export interface ILinkItemProps {
id:string|null;
title:string|null;
action:string|null;
anchorid:string|null;
trans:string|null;
}
export class LinksItem implements ILinkItemProps {
constructor (
public id: string|null = null,
public title: string|null = null,
public action: string|null = null,
public anchorid: string|null = null,
public trans: string|null = null) { }
}
export interface ILinksProps {
linkItems:Array<ILinkItemProps>;
}
export class MyList extends React.Component<ILinksProps> {
render() {
return <div>List count: {this.props.linkItems.length}</div>;
}
}
export default class App extends React.Component {
render() {
return <MyList linkItems={[
{id: '1'} as ILinkItemProps
]} />
}
}发布于 2022-07-29 13:18:51
好吧,我已经把这件事解决了,
if (!this.properties.linkItems?.push) {
this.properties.linkItems=[];
}
this.properties.linkItems.push(new LinksItem())它检查是否可以将其推送,如果没有将其设置为数组,则将其推入其中。我想知道它是否是一个bug,因为它在属性中设置为数组。
https://stackoverflow.com/questions/73151778
复制相似问题