我创建了一个自定义 ListComponent 并在 DashboardComponent 中使用。我已经导入了 ListComponent 并在其中传递了数据,列表将在 DashboardComponent 中呈现。我有创建函数来获取特定对象的 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"
}
]
}
答案 0 :(得分:1)
使用道具 在 DashboardComponent 传递函数中
<ListComponent data={userList.options} onClick = {this.onClickItem.bind(this)} />
并使用函数获取
onClickItem = (id) => {
console.log("id...",id);
}
在 ListComponent 类中调用 onPress 函数
getUserId = (id) => {
this.props.onClick(id) //Call the function
this.setState({opID:id})
};