You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

行数未知时React Native按钮激活状态的更新方法问询

动态生成组件的按钮激活状态切换实现

我通过路由参数number生成长度未知的数组,遍历数组渲染多个组件,每个组件包含两个按钮。需要实现点击其中一个按钮时,该按钮设为激活状态,另一个设为未激活状态,但不知道如何设计对应state来管理每个组件的按钮状态。

生成数组的代码

const { letters, number } = route.params
const [arr, setArr] = useState([])

useEffect(() => {
    var eachArr = []
    setArr([])
    for (let i = 1; i < Number(number) + 1; i++) {
        eachArr.push(i)
    }  
    setArr(eachArr)
}, [])

渲染组件的代码

return (
    <View style={styles.container}>
        <ScrollView>
        {
            arr.length > 0 && arr.map(num => (
                <View style={styles.placeContainer} key={num}>
                    <View style={styles.place}>
                        <Text style={{ fontWeight:'bold',letterSpacing:1 }}>{num} {letters}</Text>
                        <Feather name="check-circle" size={24} color="grey" />
                    </View>
                    <View style={{ marginVertical:10 }}>
                      <Progress color={colors.purple} progress={1} width={null} borderWidth={0} />
                    </View>
                    <View style={styles.button}>
                        <Text style={{ color:colors.white,fontFamily:'viga' }}> this {letters}</Text>
                    </View>
                    <View style={{...styles.button,backgroundColor:colors.lightPurple}}>
                        <Text style={{ color:colors.white,fontFamily:'viga' }}> this {letters}</Text>
                    </View>
                </View>
            ))
        }
        </ScrollView>
    </View>
)

解决方案

方案1:用对象存储每个组件的激活按钮标识

通过一个对象类型的state,以组件的唯一num为键,记录当前激活的按钮类型(比如用primary和secondary区分两个按钮)。

  1. 初始化状态
// 键为组件的num,值为激活按钮类型,初始为空对象
const [activeButtons, setActiveButtons] = useState({});
  1. 编写点击事件处理函数
const handleButtonClick = (num, buttonType) => {
  setActiveButtons(prevState => ({
    ...prevState,
    [num]: buttonType // 更新对应组件的激活按钮
  }));
};
  1. 修改渲染逻辑,根据状态切换样式
arr.length > 0 && arr.map(num => {
  // 默认激活第一个按钮,可根据需求调整初始值
  const currentActive = activeButtons[num] || 'primary';
  return (
    <View style={styles.placeContainer} key={num}>
      {/* 其他部分保持不变 */}
      <View 
        style={[
          styles.button,
          // 未激活时用浅色背景
          currentActive !== 'primary' ? { backgroundColor: colors.lightPurple } : {}
        ]}
        onPress={() => handleButtonClick(num, 'primary')}
      >
        <Text style={{ color:colors.white,fontFamily:'viga' }}> this {letters}</Text>
      </View>
      <View 
        style={[
          styles.button,
          currentActive === 'primary' ? { backgroundColor: colors.lightPurple } : {}
        ]}
        onPress={() => handleButtonClick(num, 'secondary')}
      >
        <Text style={{ color:colors.white,fontFamily:'viga' }}> this {letters}</Text>
      </View>
    </View>
  )
})

方案2:给数组项添加激活状态属性

直接在生成数组时,给每个元素添加记录激活按钮的属性,无需单独维护额外state。

  1. 修改数组生成逻辑
useEffect(() => {
  const eachArr = [];
  for (let i = 1; i < Number(number) + 1; i++) {
    eachArr.push({
      num: i,
      activeButton: 'primary' // 默认激活第一个按钮
    });
  }  
  setArr(eachArr);
}, []);
  1. 编写点击事件处理函数
const handleButtonClick = (index, buttonType) => {
  setArr(prevArr => {
    const newArr = [...prevArr];
    newArr[index].activeButton = buttonType;
    return newArr;
  });
};
  1. 修改渲染逻辑
arr.length > 0 && arr.map((item, index) => {
  const { num, activeButton } = item;
  return (
    <View style={styles.placeContainer} key={num}>
      {/* 其他部分保持不变 */}
      <View 
        style={[
          styles.button,
          activeButton !== 'primary' ? { backgroundColor: colors.lightPurple } : {}
        ]}
        onPress={() => handleButtonClick(index, 'primary')}
      >
        <Text style={{ color:colors.white,fontFamily:'viga' }}> this {letters}</Text>
      </View>
      <View 
        style={[
          styles.button,
          activeButton === 'primary' ? { backgroundColor: colors.lightPurple } : {}
        ]}
        onPress={() => handleButtonClick(index, 'secondary')}
      >
        <Text style={{ color:colors.white,fontFamily:'viga' }}> this {letters}</Text>
      </View>
    </View>
  )
})

注意事项

  • 两种方案都依赖组件的唯一标识(num或index)定位目标状态,确保点击操作仅影响当前组件的按钮。
  • 样式切换逻辑可根据需求调整,比如激活时添加边框、改变文字颜色等。

内容的提问来源于stack exchange,提问作者Alexander Obidiegwu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:54:20