样式组件如何转发道具?

时间:2020-02-23 15:13:27

标签: javascript reactjs react-native styled-components

我已经使用样式化组件已有一段时间了,但是老实说,我从来没有真正理解过它是如何工作的。这就是我的问题。

因此,我了解样式化的组件可以根据道具进行调整。我不明白道具的转发是如何工作的。

例如,在我的案例中,我正在使用React Native。我在输入字段中提供了一些默认道具。现在,样式化组件包装器会自动拾取默认的高度道具,但是如果我明确传递道具,它将不会拾取它,而我必须从道具中手动获取它。那是什么呢?

import React from "react";
import styled from "styled-components/native";

const StyledTextInput = styled.TextInput`
   /* Why do I have to do this for custom heights.
    * Isn't height automatically get forwarded?
    */

  /* if I comment this height style out, It takes defaultProp height but doesn't take custom height
   * I have to uncomment it for the custom height
   */

  height: ${({ height }) => height};

   ...other styles
`;

const TextInput = ({ height }) => {
  return <StyledTextInput height={height} />;
};

TextInput.defaultProps = {
  height: 50
};

export default TextInput;


// Then In some Smart Component
class App extends Component {
  render() {
    return (
      <View style={styles.app}>
        <TextInput height={200} /> // ???
        ...other stuff
      </View>
    );
  }
}

这是我的问题:

  • 样式化的组件会在什么情况下自动拾取道具?
  • 哪些道具会自动转发。
  • 此道具转发如何工作?

有关文档的讨论不多,或者我错过了。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

所有标准属性都是自动转发的道具。标准属性,例如defaultValuetype。注意React中属性的驼峰大小写符号。

如果它是someCustomAttribute属性等自定义属性,则不会直接传递给DOM。

如果某些道具对样式组件的所有实例都是 true ,则可以使用.attrs

const StyledTextInput = styled.TextInput.attrs(props => ({
  height: props.height
}))`
  // other styles
`