我在React上使用打字稿2.3.4。我收到错误TS2339:错误TS2339:类型’Readonly <{children ?: ReactNode;中不存在属性’name’;}>和只读<{}>’。当我尝试在子组件中声明属性时发生错误。如何在子组件中正确引用属性?
由于某种原因,代码未在脚本运行器中执行。
任何帮助表示赞赏。
export interface person { name: string; age: number; } interface State { personArray: person[]; } interface Props { } class ProfileData extends React.Component<{}, person> { public render() { return ( <section> <section> <h3>profile 1</h3> <div>{this.props.name}</div> </section> </section> ) } } export class Profile extends React.Component<Props, State> { public state: State; public props: Props; constructor(props: Props){ super(props); this.state = { personArray: [ { name: 'bazaaa', age: 42 }, { name: 'louis', age: 24 } ] }; } public render() { let profile1 = this.state.personArray[0]; return ( <ProfileData name={profile1.name} /> ) } } <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
您忘记name在ProfileData类定义中声明为React属性。这样的事情应该起作用:
name
ProfileData
class ProfileData extends React.Component<{name: string}, person> {