javascript - 如何在 React/React Native 的地图组件列表中独立设置状态
问题描述
我正在渲染一个 json 文件中的元素列表,我希望能够让列表中的每个组件都有自己的状态。并且独立于列表中的其他元素。我希望只有一个元素能够被点击,而不是其他任何元素,不像下图中当前显示的那样。[1]:https ://i.stack.imgur.com/vdCnR.png
这是我目前正在使用的代码。
{questions
.filter((question) => question.id === currentId)
.map((question, index) => {
return (
<>
<View key={index}>
{question.title.hasOwnProperty("main") ? (
<>
<Text style={styles.title}>{question.title.main}</Text>
<Text style={styles.subtext}>{question.title.sub}</Text>
</>
) : (
<Text style={styles.title}>{question.title}</Text>
)}
</View>
<View>
{question.answers.map((ans, i) => (
<Answer id={ans.id} key={ans.id} ans={ans} />
))}
</View>
</>
);
})}
const Answer = ({ ans, id }) => {
const [clkStatus, setClkStatus] = useState(false);
const [ansId, setAnsId] = useState(id);
return (
<Card
onPress={() => {
if (ansId === id) {
setClkStatus(true);
}
}}
status={clkStatus && "danger"}
style={{ marginBottom: 6, width: "100%" }}
>
<Text
style={{
textTransform: "uppercase",
textAlign: "center",
}}
>
{ans.value}
</Text>
</Card>
);
};
解决方案
推荐阅读
- android - 使用 Android-ViewModel (MV-VM) 避免重复的网络调用
- python - 输出问题打印
- flutter - 将原始字符串转换为字符串
- php - PHP Dependency 为 5.5,当前运行的 PHP 为 7.2
- swift - iOS 13 大型导航栏外观 + Tabbar 图像
- excel - 如何将分组结果应用于 VAR.S?
- java - 如何制作具有动态值的@JSONProperty?
- php - 忽略 PHP 到 MSSQL 连接中的记录行
- spring-boot - 使用 jdbc 和 web-starter 部署时出错
- angular - 如何使用 RxJS 运算符重构方法?