让react-native状态中的道具感知



我有一个组件在ReactNative与属性我想有一个状态,但我怎么才能实现这一点?

import React, { useState } from "react";
import {
Alert,
Text,
TouchableHighlight,
ScrollView,
View,
} from "react-native";
const MyComponent = (props) => {
const [modalVisible, setModalVisible] = useState(true);
const _closeModal = () => {
setModalVisible(false);
};
const toggleUser = async (user) => {
Alert.alert(
"Toggle",
"You sure?",
[
{
text: "Yes",
onPress: () => {
user.active = false;
},
style: "cancel",
},
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "default",
},
],
{ cancelable: false }
);
};

const activeUsers = (users) => {
return users.filter((item) => item.active);
};

return (
<View>
<ScrollView>
{activeUsers(props.users).map((u) =>
u.active == true ? (
<View>
<Text>
{u.name}
{u.active ? " - active" : null}
</Text>
<TouchableHighlight
onPress={() => {
toggleUser(u);
}}
></TouchableHighlight>
</View>
) : null
)}
</ScrollView>
</View>
);
};
export default MyComponent;

在App.js中使用:

<MyComponent users={this.state.users} ></MyComponent>

我正在寻找的可能性有用户列表只显示活跃用户。如果它是活动的,切换按钮将活动设置为false。

现在它不起作用了。是因为它没有状态吗?如果是,如何使这种状态意识到?

当然,代码做的不仅仅是这些,但这是我不能理解的一小部分。

必须为activeUsers使用这样的状态;

import React, { useState, useEffect } from "react"; // this line changed
import {
Alert,
Text,
TouchableHighlight,
ScrollView,
View,
} from "react-native";
const MyComponent = (props) => {
const [modalVisible, setModalVisible] = useState(true);
const [activeUsers, setActiveUsers] = useState([]);

// add this (I forget). dont forget to import!!
useEffect(() => {
getActiveUsers();
}, []);
const _closeModal = () => {
setModalVisible(false);
};
const toggleUser = async (user) => {
Alert.alert(
"Toggle",
"You sure?",
[
{
text: "Yes",
onPress: () => {
const active = activeUsers;
const filtered = active.filter(item => item.id !== user.id);
user.active = false;
filtered.push(user);
setActiveUsers([...new Set(filtered)]);
},
style: "cancel",
},
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "default",
},
],
{ cancelable: false }
);
};
/**
* change this function name
*/
const getActiveUsers = () => {
const active = props.users.filter((item) => item.active);
setActiveUsers(active);
};

return (
<View>
<ScrollView>
{activeUsers.map((u) =>
u.active == true ? (
<View>
<Text>
{u.name}
{u.active ? " - active" : null}
</Text>
<TouchableHighlight
onPress={() => {
toggleUser(u);
}}
></TouchableHighlight>
</View>
) : null
)}
</ScrollView>
</View>
);
};

***如果你提取一个组件和ListItem,并将user作为状态传递给它,这个过程就简单多了。

相关内容

  • 没有找到相关文章

最新更新