首页 > 解决方案 > React Native,一个按钮,每次点击三个名称

问题描述

我有这段代码,每次单击它时,它都会将按钮的名称从(KEYWORD)更改为不同的(KEYNOS)。如何使其更改为第三个值(KEYCH)。默认名称为(A、B、C...等),第一次单击显示数字(1,2...等),第二次单击显示罗马数字(I、II ...等)。我为拉丁字母、数字和罗马数字创建了三个列表。

import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

const KEYWORDS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K'];
const KEYNOS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
const KEYNCH = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
export default class App extends Component {
  state = {
    keywordsList: [],
    keynosList: [],
    keychList: [],
  };

  toggleKeyword = keyword => {
    const { keywordsList } = this.state;
    let list = keywordsList;
    let index = -1;
    if ((index = keywordsList.indexOf(keyword)) != -1) {
      list.splice(index, 1);
    } else {
      list.push(keyword);
    }
    this.setState({ keywordsList: list });
  };

  render() {
    const { keywordsList } = this.state;
    const { container, selectedKeywordStyle, buttonStyle, textStyle } = styles;
    return (
      <View style={container}>
        {KEYWORDS.map((item, index) => {
          let style, text;

          if (keywordsList.find(element => element === item)) {
            style = selectedKeywordStyle;
            text = KEYNOS[index];
          } else {
            style = buttonStyle;
            text = item;
          }

          return (
            <TouchableOpacity
              key={index} // make sure you assign a unique key for each item
              style={style}
              onPress={() => this.toggleKeyword(item)}>
              <Text style={textStyle}>{text}</Text>
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    flexWrap: 'wrap',
    paddingTop: 50,
  },
  textStyle: {
    color: 'white',
    fontSize: 16,
    padding: 8,
    textAlign: 'center',
  },
  buttonStyle: {
    width: '30%',
    backgroundColor: 'green',
    borderRadius: 15,
    margin: 5,
  },
  selectedKeywordStyle: {
    width: '30%',
    backgroundColor: 'red',
    borderRadius: 15,
    margin: 5,
  },
});

标签: javascriptreactjsreact-native

解决方案


通过使用不同的方法和数据结构,我得到了一些工作:

import React, {Component} from 'react';
import {Text, View, StyleSheet, TouchableOpacity} from 'react-native';

const DATA = [
  ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K'],
  ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'],
];

const defaultKeys = Array.apply(null, Array(10)).map(
  Number.prototype.valueOf,
  0,
);

function getStyleForKey(key) {
  const colors = ['green', 'red', 'blue'];
  return {...styles.defaultButtonStyle, backgroundColor: colors[key]};
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keys: defaultKeys,
    };
  }

  toggleKeyword = (key, index) => {
    let tempKeys = [...this.state.keys];
    if (key < DATA.length - 1) {
      tempKeys[index]++;
    } else {
      tempKeys[index] = 0;
    }
    this.setState({keys: tempKeys});
  };

  render() {
    const {keywordsList} = this.state;
    const {container, selectedKeywordStyle, buttonStyle, textStyle} = styles;
    return (
      <View style={container}>
        {this.state.keys.map((key, index) => {
          let style = getStyleForKey(key);

          return (
            <TouchableOpacity
              key={index}
              style={style}
              onPress={() => this.toggleKeyword(key, index)}>
              <Text style={textStyle}>{DATA[key][index]}</Text>
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    flexWrap: 'wrap',
    paddingTop: 50,
  },
  textStyle: {
    color: 'white',
    fontSize: 16,
    padding: 8,
    textAlign: 'center',
  },
  defaultButtonStyle: {
    width: '30%',
    backgroundColor: 'green',
    borderRadius: 15,
    margin: 5,
  },
});

所以想法是创建一个键数组,其中数组中的每个键都有一个值 from 0to DATA.length - 1。该数组存储在keys示例中的状态中。的默认值keys是一个数组,其起始键0的次数与字符集中的项目数一样多。

然后在渲染中,我们循环遍历keys每个键,我们使用该键的值从中检索正确的字符集,DATA并使用循环的当前索引从该字符集中选择一个特定字符。

该函数现在唯一要做的toggleKeyword就是增加一个键的值并检查该键是否已达到其“最大值”(在我们超出DATA数组边界之前的值)。当键是它的最大值时,我们将键的值重置为0.


推荐阅读