[英]How can I pass props from one component to another in typescript?
[英]How can I pass data from a component array to an another component with props?
我需要一点帮助。 我正在从事一个在 React 中使用 Class 组件的项目,但我遇到了一个问题。
如何使用道具传递数据?
例如,假设我有一个 Component 在 state 中有一个数组:
import React,{Component} from "react";
class CarList extends Component{
constructor(props){
super(props);
this.state = {
carList: ['Jeep', 'Kwid','HB20','Ônix', 'Prisma', 'Gol quadrado']
}
}
render(){
return(
<div>
</div>
);
}
}
export default CarList;
现在我必须在 Select 标签内的选项标签中调用此数组。
让我们想象一下这个组件:
import React from "react";
import { Component } from "react";
import CarList from "./components/Datas";
class App extends Component{
render(){
return(
<div>
<p>I got it! Here is the car list:</p>
<select>
{this.state.CarList.map( (item,x)=>{
return(
<option key={x}>{item}</option>
)
})}
</select>
</div>
)
}
}
export default App;
这段代码不起作用。 console.log 说:“未捕获的类型错误:this.state 为空”
我知道我可以用我的数据创建一个 div 并调用,但我必须使用道具在组件之间传递数据。
如何使用道具创建回调 function 来解决此问题?
你好!
我尝试使用 this.state 进行调用,但出现“this.state 未定义”
要将数据作为 props 传递,您必须像这样从父组件将其传递给子组件:
class ParentComponent extends React.Component {
state = {
carList: [],
};
constructor(props) {
super(props);
this.state = {
carList: ['Jeep', 'Kwid', 'HB20', 'Ônix', 'Prisma', 'Gol quadrado'],
};
}
render() {;
return (
<div>
<ChildComponent carList={this.state.carList || []} />
</div>
);
}
}
然后它可以在您的子组件中使用this.props
。
你可以像这样在子组件中使用这个道具:
class ChildComponent extends React.Component {
render() {
return (
<div>
{this.props.carList.map((cars, index) => {
return (
<span key={index}>
{cars}
<br />
</span>
);
})}
</div>
);
}
}
编辑 -
如果您想查看源代码: https://stackblitz.com/edit/react-ts-ddcylu?file=Parent.tsx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.