javascript - 使用循环检查组件的样式

标签 javascript reactjs loops react-native

我使用循环创建了一组按钮。这些按钮的背景颜色一个一个地改变,一次一个按钮。调用函数时,有没有办法获取背景颜色为黑色的按钮的键。

export default class App extends Component<Props> {
  constructor(props) {
        super(props);
        this.state = {
            selectedControl: 0,
            controls: ["TITLE1", "TITLE2", "TITLE3"]
        };

    }

  componentDidMount() {
        this.timerHandle = setInterval(() => {
            this.setState(({selectedControl, controls}) =>
               ({selectedControl: (selectedControl + 1) % controls.length})
            );
        }, 1000);
    }

  render() {
    const {selectedControl, controls} = this.state;
    return (
      <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap',  justifyContent: 'space-evenly',
      alignItems: 'stretch' }}>
      {controls.map((control, index) => (
          <Button key={control}  title={control} buttonStyle={index === selectedControl ? styles.highlighted : styles.buttonStyle}/>
          ))}
    </View>
    );
  }
}

const styles = StyleSheet.create({
  buttonStyle: {
     height: '100%', 
  },
  highlighted: {
    height: '100%',
    backgroundColor: 'black', 
  }
});

最佳答案

按钮键设置为control。因此,检查按钮何时在 render 中突出显示(即 index === selectedControl)并且按钮的键是 control

<View style={{
  flex: 1,
  flexDirection: 'row',
  flexWrap: 'wrap',
  justifyContent: 'space-evenly',
  alignItems: 'stretch'
}}>
  {controls.map((control, index) => {
    if (index === selectedControl) {
      console.log({"key": control}) /* <-- here */
    }
    return <Button key={control}  title={control} buttonStyle={index === selectedControl ? styles.highlighted : styles.buttonStyle}/>
  })}
</View>

关于javascript - 使用循环检查组件的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432901/

相关文章:

javascript - NextJS 错误 : Component props are undefined when building the project (everything works fine on dev mode)

javascript - 将函数分配给 JavaScript 按钮数组

javascript - 切换类别并向下滑动

javascript - twilio javascript api 通过 get call sid 这可能吗?

javascript - 在 JavaScript 和 xml 中计算天数

Javascript:找到前n个素数

android - 在 android 设备中改变方向时不显示布局的立即变化 react native

javascript - 在 react 中使用异步等待从火力存储中检索图像

jquery:如何循环一个div

c - Loop后输出错误是strcat引起的?