首页 > 解决方案 > 如何在 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>
);

};

标签: javascriptreactjsreact-nativefunction

解决方案


推荐阅读