[英]How to pass Array of Objects from Parent Component to Child Component in react
[英]How to pass id child to parent component in react?
我创建了一个自定义ListComponent并在DashboardComponent中使用。 我已经导入了 ListComponent 并在其中传递了数据,并且列表将呈现在 DashboardComponent 中。 我创建了 function 来获取特定 object 的 id。 因此,每当我单击任何列表时,都会在ListComponent中获得 id。 但是,我想在我无法做到的 DashboardComponet 上传递这个 id。
列表组件代码:
import React, { Component } from "react";
import {Text,View} from "react-native";
import { List,ListItem} from "native-base";
export default class ListComponent extends Component {
constructor(props) {
super(props);
this.state = {
opID: "",
};
}
getUserId = (id) => {
console.log("id",id);
this.setState({opID:id})
};
render() {
return (
<View style={optionUI.container}>
<List>
{this.props.data.map((Opt, i) => (
<ListItem
key={Opt.id}
opID = {this.props.opID}
noBorder
onPress={() =>
this.getUserId(Opt.id)
}
>
<Text>{Opt.title}</Text>
</ListItem>
))}
</List>
</View>
);
}
}
仪表板组件:
import React, { StrictMode, Component } from "react";
import { View} from "react-native";
import ListComponent from "../components/Option";
export default class DashboardComponent extends Component {
constructor(props) {
super(props);
this.state = {
userList: [...data...],
};
}
componentDidMount() {
}
render() {
const {userList} = this.state;
console.log("users",this.props);
return (
<StrictMode>
<View style={dashboardUI.optionSection}>
<ListComponent data={userList.options} />
</View>
</StrictMode>
);
}
}
数据:
userList={
"options": [
{
"id": 1,
"optId":1,
"title": "Reliance Industries Limited",
"subtitle": "Multinational conglomerate company"
},
{
"id": 2,
"optId":2,
"title": "Aditya Birla Group",
"subtitle": "Corporate group company"
},
{
"id": 3,
"optId":3,
"title": "Adani Group",
"subtitle": "Multinational conglomerate company"
},
{
"id": 4,
"optId":4,
"title": "Piramal Group",
"subtitle": "Conglomerate company"
},
{
"id": 5,
"optId":5,
"title": "Hindustan Zinc",
"subtitle": "Mining company"
}
]
}
在 DashboardComponent 中使用 props 传递 function
<ListComponent data={userList.options} onClick = {this.onClickItem.bind(this)} />
并与 function
onClickItem = (id) => {
console.log("id...",id);
}
在 ListComponent class 中调用 function onPress
getUserId = (id) => {
this.props.onClick(id) //Call the function
this.setState({opID:id})
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.