将react-native-vector-icons / FontAwesome与样式化组件一起使用

时间:2018-10-07 12:50:49

标签: react-native font-awesome styled-components

我正在重构一些React Native代码以使用styled-components,但是在设计FontAwesome图标时遇到了麻烦。我收到诸如

之类的错误
  

styledComponents2.default.IconFontAwesome不是函数

因此,我了解到this GitHub issue,我需要包装组件并将className道具传递到per the docs on extending custom components下。所以我有这个:

import React from 'react';
import {
  Text,
  TouchableOpacity,
} from 'react-native';
import PropTypes from 'prop-types';
import IconFontAwesome from 'react-native-vector-icons/FontAwesome';
import styled from 'styled-components';

const StyledTouchableOpacity = styled.TouchableOpacity`
  width: ${props => (props.large ? '100%' : '80%')};
  height: ${props => (props.large ? '80px' : '60px')};
  font-size: ${props => (props.large ? '18px' : '15px')};
  background: '#f1d746';
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
`;

const StyledText = styled.Text`
  font-size: 15;
  font-weight: bold;
`;

const StylableIcon = ({ className }) => (
  <IconFontAwesome className={className} />
);

const StyledIconFontAwesome = styled.StylableIcon`
  font-size: 15;
  padding: 10px;
`;

const Button = (props) => {
  let _icon = null;

  if (props.icon) {
    _icon = (
      <StyledIconFontAwesome name={props.icon} />
    );
  }

  return (
    <StyledTouchableOpacity>
      <StyledText>{props.text}</StyledText>
      {_icon}
    </StyledTouchableOpacity>
  );
};

Button.defaultProps = {
  icon: null,
};

Button.propTypes = {
  icon: PropTypes.string,
};

export default Button;

这会导致类似的错误

  

styledComponents2.default.StylableIcon不是函数

关于我在这里做错什么的任何提示?谢谢大家。

1 个答案:

答案 0 :(得分:0)

确定可以使用:

import React from 'react';
import {
  Text,
  TouchableOpacity,
} from 'react-native';
import PropTypes from 'prop-types';
import IconFontAwesome from 'react-native-vector-icons/FontAwesome';
import styled from 'styled-components';

const StyledTouchableOpacity = styled.TouchableOpacity`
  width: ${props => (props.large ? '100%' : '80%')};
  height: ${props => (props.large ? '80px' : '60px')};
  font-size: ${props => (props.large ? '18px' : '15px')};
  background: '#f1d746';
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
`;

const StyledText = styled.Text`
  font-size: 15;
  font-weight: bold;
`;

const StyledIconFontAwesome = styled(IconFontAwesome)`
  font-size: 15;
  padding: 10px;
`;

const Button = (props) => {
  let _icon = null;

  if (props.icon) {
    _icon = (
      <StyledIconFontAwesome name={props.icon} />
    );
  }

  return (
    <StyledTouchableOpacity>
      <StyledText>{props.text}</StyledText>
      {_icon}
    </StyledTouchableOpacity>
  );
};

Button.defaultProps = {
  icon: null,
};

Button.propTypes = {
  icon: PropTypes.string,
};

export default Button;

这里有两个解决方法:

  1. 必须使用语法styled(Something)而非styled.Something(感谢@bennygenel)
  2. 包装器StylableIcon是不必要的。我可以直接致电styled(IconFontAwesome)