React按钮组的原生按钮映射

时间:2018-01-24 15:18:55

标签: javascript css button react-native

试图找出如何仅在第一个和最后一个按钮上更改样式。
如何告诉按钮哪一个是哪个?
初学者在JS和React / React Native试图找到自己的方式。目前两端都没有圆形按钮。
子项中的Button元素是我自己在TouchableOpacity上的包装器,只接受buttonStyles的一个对象。
任何帮助表示赞赏。

父组件:

export class Rating extends React.Component {

  ratings = [
    { text: '1' },
    { text: '2' },
    { text: '3' },
    { text: '4' },
    { text: '5' },
  ];

  onButtonPress = (e) => {
    console.log(e.target.value);
  };

  render() {
    return (
      <View>
        {this.ratings.length && (
          this.ratings.map((rating, index) => (
            <View key={index}>
              <RatingButton rating={rating} onButtonPress={this.onButtonPress} />
            </View>
          ))
        )
      }
      </View>

    );
  }
}

子组件:

const buttonStyles = () => {
  const allButtons = {
    backgroundColor: sc.colors.white.white,
    borderWidth: 1.5,
    borderColor: sc.colors.blue.darker1,
    padding: sc.padding.lg,
  };

  const startButton = {
    borderTopLeftRadius: sc.borderRadius.sm,
    borderBottomLeftRadius: sc.borderRadius.sm,
    borderRightWidth: 0.75,
    ...allButtons,
  };

  const endButton = {
    borderTopRightRadius: sc.borderRadius.sm,
    borderBottomRightRadius: sc.borderRadius.sm,
    borderLeftWidth: 0.75,
    ...allButtons,
  };
  return StyleSheet.create({
    allButtons,
    startButton,
    endButton,
    buttonText: {
      color: sc.colors.blue.darker1,
      fontSize: sc.font.size.largeContent,
    },
  });
};

class RatingButton extends React.Component {

  render() {
    const { onButtonPress, rating } = this.props;
    const styles = buttonStyles();
    return (
      <Button
        buttonStyles={styles.allButtons}
        textStyles={styles.buttonText}
        onPress={onButtonPress}
      >
        {rating.text}
      </Button>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

ratings变量的内部,您可以存储样式的另一个属性,如下所示:

ratings = [
    { text: '1', style: {backgroundColor:'red'} },
    { text: '2' },
    { text: '3' },
    { text: '4' },
    { text: '5', backgroundColor: 'yellow' },
  ];

然后在<RatingButton/>内,您可以将样式添加到元素

<Button
        buttonStyles={styles.allButtons}
        textStyles={styles.buttonText}
        onPress={onButtonPress}
        style={rating.style}
      >
        {rating.text}
</Button>

注意:您还可以通过rating变量传递课程。

ratings = [
    { text: '1', buttonStyle: 'startButton' },
    { text: '2' },
    { text: '3' },
    { text: '4' },
    { text: '5', buttonStyle: 'endButton' },
  ];

并设置你的风格:

<Button
        buttonStyles={ratings.buttonStyle?styles[rating.buttonStyle]:styles.allButtons}
        textStyles={styles.buttonText}
        onPress={onButtonPress}
        style={rating.style}
      >
        {rating.text}
</Button>