美文网首页
[学习笔记] TypeScript+React 试水 - 踩坑记

[学习笔记] TypeScript+React 试水 - 踩坑记

作者: 玛丽莲做梦 | 来源:发表于2019-12-04 14:08 被阅读0次
  • interface 命名

程序报错:interface name must start with a capitalized I
interface 的命名必须以 大写 I 开头。

  • 组内的导入源

程序报错:Import sources within a group must be alphabetized
组内的导入源必须按照字母顺序依次导入。
举个错误例子:

import Home from "./Home"
import About from "./About"

正确写法:

import About from "./About"
import Home from "./Home"
  • 类方法 render 的权限

程序报错:The class method 'render' must be marked either 'private', 'public', or 'protected'
类方法“render”必须标记为“private”、“public”或“protected”。
讲一下这条错误出现的情况:
我在 index.tsx 中引入ES6 class 定义的子组件。子组件中的render() 函数前没有 privatepublicprotected 程序会报错。但是在我这个情况下,只有使用 public 前缀时代码可以正常运行,使用其他两个前缀程序仍然报错(其他错误)无法运行,这个情况目前还未探究。

  • 组件传递的 Props

组件传递 Props 和 javascript 不同的是,需要通过参数的形式显示传递 Props 组件才可以获取到。
这里举一个 类组件 的例子:

// ./src/components/Person.tsx
interface IProps {
  name: string;
  age: number
}

class Person extends React.Component<IProps>{
  constructor(props: IProps) {
    super(props)
  }
}

public render() {
  return (
    <div>
      <p>姓名:{ this.props.name }</p>
      <p>年龄:{ this.props.age }</p>
    </div>
  )
}


// ./src/index.tsx
ReactDOM.render(
  <div>
    <Person name="张三三" age={11} />
  </div>,
 document.getElementById("root") as HTMLElement
)

这里再举一个 函数式组件 的例子:

// Person.tsx
// 父组件与上面例子相同
interface IProps {
  name: string;
  age: number;
}

function Person( { name, age }: IProps ) {
  return (
    <div>
      <p>姓名:{ name }</p>
      <p>年龄:{ age }</p>
    </div>
  )
}
  • 组件中的 State

组件的 State 与 Props 类似,也是需要通过定义 State 接口的方式来设置 State。
这里也举一个例子:

interface IState {
  currentTime: Date;
}

interface IProps {
  country: string;
}

class Zone extends React.Component<IState, IProps> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      curTime: new Date
    }
  }

  public render() {
    return (
      <div>
        国家:{ this.props.country }, 当前时间:{ this.state.curTime.toString() }
      </div>
    )
  }
}

相关文章

网友评论

      本文标题:[学习笔记] TypeScript+React 试水 - 踩坑记

      本文链接:https://www.haomeiwen.com/subject/lpgkgctx.html