Reactjs,Typescript - 子组件上不存在属性 [英] Reactjs, Typescript - property does not exist on child component

查看:39
本文介绍了Reactjs,Typescript - 子组件上不存在属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 中使用 typescript 2.3.4.我收到错误 TS2339: error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode;}> &只读<{}>'.当我尝试在子组件中声明属性时会发生错误.如何在子组件中正确引用该属性?

I'm using typescript 2.3.4 with React. I'm getting the error TS2339: error TS2339: Property 'name' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'. The error happens when I try to declare the property in a child component. How do I reference the property, properly in the child component?

由于某种原因,代码没有在脚本运行器中执行.

For some reason the code is not executing in script runner.

感谢任何帮助.

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>

推荐答案

您忘记在 ProfileData 类定义中将 name 声明为 React 属性.这样的事情应该可以工作:

You forgot to declare name as a React property in the ProfileData class definition. Something like this should work:

class ProfileData extends React.Component<{name: string}, person> {

这篇关于Reactjs,Typescript - 子组件上不存在属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆