Javascript 使用React with typescript时未定义this.props.xxx,但在ES5中工作正常?
最近我开始学习ES5的react,但现在尝试使用Type 我的应用程序中的脚本。谁能告诉我为什么我不能打印 使用{this.props.people}的值,但当我 使用{this.state.people}.我从这个网站上取了一个例子。 请告诉我这里缺少什么Javascript 使用React with typescript时未定义this.props.xxx,但在ES5中工作正常?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,最近我开始学习ES5的react,但现在尝试使用Type 我的应用程序中的脚本。谁能告诉我为什么我不能打印 使用{this.props.people}的值,但当我 使用{this.state.people}.我从这个网站上取了一个例子。 请告诉我这里缺少什么 import*as React from'React'; 类关于扩展React.Component{ 构造器(道具:任何){ 超级(道具); console.log(关于); const people=[]; for(设i=0;i( 您
import*as React from'React';
类关于扩展React.Component{
构造器(道具:任何){
超级(道具);
console.log(关于);
const people=[];
for(设i=0;i<10;i++){
人,推({
姓名:我,,
国家:i+i
});
}
this.state={people};
}
公共渲染(){
返回(
{this.props.people.map((person:any,index:number)=>(
您好,{person.country}的{person.name}
))}
);
}
}
导出默认值约为代码>因为这个.props.people
是在父组件发送people prop时填充的this.state.people
是可访问的,因为您正在构造函数中设置它
它与ES5
或ES6
没有任何关系。顺便说一句,您正在使用箭头函数中的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>
)
}
}
类父级扩展React.Component{
渲染(
返回(
)
)
}
子类扩展了React.Component{
建造师(道具){
此.state={
人物:[5,6,7]
}
}
render(){
报税表(
{this.props.people}//将呈现来自父级的[1,2,3]
{this.state.people}//将从构造函数中呈现[5,6,7]
)
}
}
这是因为在您的示例中,人物道具从未被传递,它只是在构造函数中生成并设置为状态,您必须使用This.state.people
如果你想使用道具,你必须通过父组件传递人物。看看南都……是的,你完全正确,这个例子非常清楚……但我有点困惑。。。假设我的“About”类在我的示例中是父类,并且我想将数据传递给子类。那么我会像这样发送它吗?在About
的渲染方法中,您需要调用
,是的。然后在人员
组件中,您可以通过this.props.People
访问人员。