gpt4 book ai didi

javascript - this.props.xxx 在将 React 与 typescript 一起使用时未定义但在 ES5 中正常工作?

转载 作者:搜寻专家 更新时间:2023-11-01 05:09:20 25 4
gpt4 key购买 nike

最近我开始学习使用 ES5 使用react,但现在尝试使用 Type 我的应用程序中的脚本。谁能告诉我为什么我无法打印 使用 {this.props.people} 的值,但它在我时按预期工作 使用 {this.state.people}. 我已经从这个站点中获取了示例。 请建议我这里缺少什么?

Site

import * as React from 'react';

class About extends React.Component<any, any> {
constructor(props: any) {
super(props);
console.log(About);
const people = [];

for (let i = 0; i < 10; i++) {
people.push({
name: i,
country: i + i
});
}

this.state = {people};
}
public render() {
return (
<div>
{this.props.people.map((person: any, index: number) => (
<p key={index}>Hello, {person.name} from {person.country}!</p>
))}
</div>
);
}
}
export default About;

最佳答案

因为 this.props.people 是在您的父组件发送 people Prop 时填充的东西。 this.state.people 是可访问的,因为您在构造函数中设置了它。

而且它与 ES5ES6 无关。顺便说一句,您正在使用箭头函数中的 ES6

class Parent extends React.Component {
render(
return (
<Child people=[1, 2, 3] />
)
)
}

class Child extends React.Component {
constructor(props) {
this.state = {
people: [5, 6, 7]
}
}

render() {
return (
<div>
{this.props.people} // Will render [1, 2, 3], coming from Parent
{this.state.people} // Will render [5, 6, 7], coming from Constructor
</div>
)
}
}

关于javascript - this.props.xxx 在将 React 与 typescript 一起使用时未定义但在 ES5 中正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47613373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com