【问题标题】:Property 'age' does not exist on type 'Home' React/TypeScript类型“Home”React/TypeScript 上不存在属性“age”
【发布时间】:2020-05-15 04:29:47
【问题描述】:

React/TS 新手在这里。我正在 SPFX 框架内构建一个 React 组件。 this.age 出现错误,但 props.age 工作正常。

我收到一个 TypeScript 错误:

“Home”类型 React/TypeScript 上不存在属性“Age”

代码:

import * as React from 'react';

export interface IHomeProps {
  name: string;
  age: number;
  user: any;
}

export class Home extends React.Component<IHomeProps> {

  public constructor(props) {
    super(props);
    this.age = props.age;
  }

  public onMakeOlder() {
    this.age += 3;
  }

  public render() {

    console.log(this.props);

    return (
      <nav className="navbar">
        <div className="container">
          Your name is {this.props.name}, your age is {this.age}.
          {this.props.user.name}
          {this.props.user.hobbies.map((hobbie, i) => 
            <li key={i}>{hobbie}</li>
          )}
          <hr/>
          <button onClick={() => this.onMakeOlder()}>Make me older!</button>
        </div>
      </nav>
    );
  }

}

知道我哪里出错了吗? :/

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你必须在类中声明属性。

    import * as React from 'react';
    
    export interface IHomeProps {
      name: string;
      age: number;
      user: any;
    }
    
    export class Home extends React.Component<IHomeProps> {
    
      private age: number;
      
      public constructor(props) {
        super(props);
        this.age = props.age;
      }
    
      public onMakeOlder() {
        this.age += 3;
      }
    
      public render() {
    
        console.log(this.props);
    
        return (
          <nav className="navbar">
            <div className="container">
              Your name is {this.props.name}, your age is {this.age}.
              {this.props.user.name}
              {this.props.user.hobbies.map((hobbie, i) => 
                <li key={i}>{hobbie}</li>
              )}
              <hr/>
              <button onClick={() => this.onMakeOlder()}>Make me older!</button>
            </div>
          </nav>
        );
      }
    
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    【讨论】:

    • 谢谢! - 我会在允许的时候接受答案。
    • 好的,很高兴能帮到你
    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2020-12-11
    • 2023-04-02
    相关资源
    最近更新 更多