账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    typescript与react基础问题
    47
    0
    import * as React from 'react'
    import * as Reactdom from 'react-dom'
    
    interface Person {
      firstName: string;
      middleName?: string;
      lastName: string;
    }
    
    class Greeter extends React.Component<Person> {
      fullName: string
      constructor (props) {
        super(props)
        this.setFullName(props.person)
      }
      setFullName = function<Person>(person) {
        this.fullName = `${person.firstName}·${person.lastName}`
      }
      sayName = ():string => this.fullName
      render () {
        return (
          <div>{this.sayName}</div>
        )
      }
    }
    
    const jor:Person = {
      firstName: 'michale',
      lastName: 'jordan',
    }
    
    Reactdom.render(<Greeter person={jor} />, document.getElementById('#app') as HTMLElement)

    为什么会提示下面这个?

    [ts]
    不能将类型“{ person: Person; }”分配给类型“IntrinsicAttributes & IntrinsicClassAttributes<Greeter> & Readonly<{ children?: ReactNode; }> & R...”。
    不能将类型“{ person: Person; }”分配给类型“Readonly<Person>”。
    类型“{ person: Person; }”中缺少属性“firstName”。

    这个是什么意思

    1
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 余生长醉 普通会员 1楼

      在使用TypeScript和React进行开发时,可能会遇到一些基础问题。以下是一些常见的问题及其解决方案:

      1. 类型错误:TypeScript允许你定义函数或类,但在编译时会自动检查类型。如果类型不正确,编译器会抛出错误。为了避免这种错误,你需要确保你的函数或类的类型是正确的。

      2. 模块导入:React使用React库来创建组件。然而,TypeScript并没有内置的模块导入功能。你需要手动导入React库,然后在组件的构造函数中导入它。例如,如果你有一个名为MyComponent的组件,你可以在MyComponent的构造函数中这样导入它:

      typescript import React from 'react';

      1. 应用到特定组件:如果你需要将某些代码应用到特定的组件中,你需要使用React的useContext或useReducer等钩子。例如,如果你有一个名为MyContext的全局上下文,你可以这样使用它:

      ```typescript import React from 'react'; import MyContext from './MyContext';

      function MyComponent() { const { myContextValue } = useContext(MyContext);

      return (

      {myContextValue}
      ); }

      export default MyComponent; ```

      1. 使用React的状态管理库:React有很多状态管理库,如Redux、MobX等。这些库可以帮助你更好地管理应用程序的状态。如果你还没有使用这些库,你可以先了解一下它们的工作原理和使用方法。

      2. 使用React的生命周期方法:React有一些生命周期方法,如componentWillMount、componentWillReceiveProps等,可以帮助你在组件加载时或组件改变时进行处理。你可以使用这些方法来处理一些常见的React事件。

      以上是一些常见的TypeScript和React基础问题及其解决方案。如果你遇到其他问题,可以查阅React的官方文档或在线教程。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部