使用样式化组件的React Native中的动态样式按钮

Chr*_*man 4 button react-native styled-components

Button组件通常由包含TouchableHighlight(或其他可触摸)的Text元素组成.我正在尝试创建一个使用样式组件设置样式的Button组件,但我无法让我的样式动态响应道具.

按钮组件

下面,我创建了一个类似于基于样式组件文档中的道具示例的Adapting的Button组件.

import React from 'react';
import { Text, TouchableHighlight } from 'react-native';
import styled from 'styled-components/native';

const colors = {
    accent: '#911',
    highlight: '#D22',
    contrast: '#FFF',
}

const Label = styled.Text`
  color: ${props => !props.outline ? colors.contrast : colors.accent};
  font-weight: 700;
  align-self: center;
  padding: 10px;
`

const ButtonContainer = styled.TouchableHighlight`
  background-color: ${props => props.outline ? colors.contrast : colors.accent};
  width: 80%;
  margin-top: 5px;
  border-color: ${colors.accent};
  border-width: 2px;
`

const Button = (props) => {
    return (
        <ButtonContainer
            onPress={props.onPress}
            underlayColor={colors.highlight}
        >
            <Label>
                {props.children}
            </Label>
        </ButtonContainer>
    );
};

export default Button;
Run Code Online (Sandbox Code Playgroud)

按钮用法

导入后,我正在使用这样的按钮......

    <Button
      outline
      onPress={() => console.log('pressed')}>
      Press Me!
    </Button>
Run Code Online (Sandbox Code Playgroud)

预期结果

所以,我希望我的按钮看起来像这样......

在此输入图像描述

实际结果

但它看起来像这样...... 在此输入图像描述

到目前为止我做了什么来解决问题

当我使用react-devtools进行检查时,我可以看到outline道具被传递给Button组件.

在此输入图像描述

但道具并没有传给任何一个孩子

在此输入图像描述

文档中的Passed Props部分说,"样式组件传递了他们所有的道具",但我想不是一路下来的?

我的问题

我需要更改什么才能根据它的道具动态设置Button的样式?

sat*_*164 6

在这里你有:

const Button = (props) => {
    return (
        <ButtonContainer underlayColor={colors.highlight}>
            <Label>
                {props.children}
            </Label>
        </ButtonContainer>
    );
};
Run Code Online (Sandbox Code Playgroud)

如果ButtonContainer是一个正常的React组件,你不会期望props传递Button给它自动传递给ButtonContainer.你必须这样<ButtonContainer underlayColor={colors.highlight} {...props} />做.

实际上ButtonContainer是一个普通的React组件,唯一的区别是你使用HOC预先应用了一些样式.

此外,如果你将这个React.createElement调用到调用,你可以看到无法props自动传递,因为Function的参数不会自动传递给它内部的函数调用.

const Button = (props) => {
    return React.createElement(ButtonContainer, { underlayColor: colors.highlight }, ...);
};
Run Code Online (Sandbox Code Playgroud)

这没什么特别的styled-components.你只需要自己传递道具ButtonContainer,以及Label.

所以你要重写你的代码:

const Button = (props) => {
    return (
        <ButtonContainer underlayColor={colors.highlight} onPress={props.onPress} outline={props.outline}>
            <Label outline={props.outline}>
                {props.children}
            </Label>
        </ButtonContainer>
    );
};
Run Code Online (Sandbox Code Playgroud)

从技术上讲,React组件可以将道具传递给它的子项,因此ButtonContainer可以将它们传递给Label使用React.ChildrenReact.cloneElementAPI.但是ButtonContainer出于显而易见的原因不这样做,例如你不想要underlayColor并自动onPress传递Label.这会导致许多令人困惑的错误.