子组件

时间:2017-06-11 22:29:20

标签: reactjs typescript

我使用带有React的typescript 2.3.4。我收到错误TS2339:错误TS2339:属性'名称'类型' Readonly< {children?:ReactNode; }> &安培;只读< {}>&#39 ;.当我尝试在子组件中声明属性时发生错误。如何在子组件中正确引用属性?

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

感谢任何帮助。



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}
            />
        )
    }
}
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:15)

您忘记在name类定义中将ProfileData声明为React属性。这样的事情应该有效:

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