2339个java_TS2339:'Home'类型中不存在属性'props' (TS2339: Property 'props' does not exist on type 'Home')...

It seems that Typescript needs to know the shape of the props and state passed to a component. If you really need to avoid Typescript from enforcing this rule, then, the component that needs access to the props or state passed to it has to extend React.Component instead of just React.Component. This means the component in question must accept any kind of shape for both props and state.

Try this

import * as React from "react";

import * as ReactDOM from 'react-dom';

export class Home extends React.Component {

render() {

console.log(this.props)

return (

Working

)

}

}

class App extends React.Component{

render() {

return (

)

}

}

ReactDOM.render(, document.getElementById("app"));

You can also view the demo here

If you actually wanted to enforce the shape of the props and/or state you would then have to define these shapes with an interface. Here is an example of the same code above that enforces the shape of the props:

import * as React from "react";

import { render } from "react-dom";

interface Props {

value:string,

name:string

}

export default class Home extends React.Component{

render() {

console.log(this.props)

return (

Working. The props values are: {this.props.value} {this.props.name}

)

}

}

class App extends React.Component {

render() {

return (

)

}

}

render(, document.getElementById("root"));

Now, here you could never be able to add any other prop to the Home component without defining it in the Props interface. For example doing something like: would not compile because somethin is not defined in the interface.

To enforce the shape of the state you'd have to do the same thing as for the props; define a contract (interface).

Also, note that you still need to access your props via this NOT Props as this is just a definition of structure not holder of values themselves.

You can view the demo for this alternative here

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值