【问题标题】:Check component 's style using a loop使用循环检查组件的样式
【发布时间】:2019-06-03 18:42:51
【问题描述】:

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

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', 
  }
});

【问题讨论】:

    标签: javascript reactjs loops react-native


    【解决方案1】:

    按键设置为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>
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2021-11-23
      相关资源
      最近更新 更多