反应本机渲染按钮

时间:2020-10-19 06:17:43

标签: reactjs react-native use-state react-usememo

我想我知道这个问题,但是我没有解决办法, 所以我有这些按钮是在useState arrray上循环创建的

const [booleanMonth,setMonth]=useState([
  {key:0,value:'January',title:'Jan',checked:false},
  {key:1,value:'February',title:'Feb',checked:false},
  {key:2,value:'March',title:'Mar',checked:false},
  {key:3,value:'April',title:'Apr',checked:false},
  {key:4,value:'May',title:'May',checked:false},
  {key:5,value:'June',title:'Jun',checked:false},
  {key:6,value:'July',title:'Jul',checked:false},
  {key:7,value:'August',title:'Aug',checked:false},
  {key:8,value:'September',title:'Sep',checked:false},
  {key:9,value:'October',title:'Oct',checked:false},
  {key:10,value:'November',title:'Nov',checked:false},
  {key:11,value:'December',title:'Dec',checked:false}
])

然后渲染按钮:

const createButtonMonth = useMemo(() =>{
console.log('createButtonMonth')
return (<View style={styles.containerForButtons2}>
        {
          booleanMonth.map((item,key) => 
            <View key={item.key} style={styles.buttonFilter3}>
            <Button style={styles.buttonFilter3}
            title={item.title} 
            value={booleanMonth[item.key].checked} 
            onCheckColor='red'
            color={booleanMonth[item.key].checked==true ? 'green':'black'}
            onPress={()=>onPressMonthFilter(booleanMonth[item.key].key,booleanMonth[item.key].checked)}
            /></View>)
        }
        </View>)
  },[booleanMonth])

现在这是onPress函数,它将检查状态更改为true或false,因此应该 更改这些按钮的颜色

const onPressMonthFilter = (keyMonth,statusMonth) =>{
if(booleanMonth[keyMonth].checked==true){
  booleanMonth[keyMonth].checked=false
  console.log(booleanMonth)
  setMonth(booleanMonth)
}else{
  booleanMonth[keyMonth].checked=true
  console.log(booleanMonth)
  setMonth(booleanMonth)
}
setMonth(booleanMonth)
}

在控制台日志中,它返回带有选中的true或false,这表示我的代码是正确的,但是没有呈现正确的颜色,false = black,true = green

请在这里帮助新手reactjs用户:<< / p>

1 个答案:

答案 0 :(得分:1)

我认为是由于记忆。

尝试删除useMemo,因为它会捕获组件并阻止其重新呈现。