样式组件如何转发 props?

Aye*_*har 5 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>
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

这是我的问题:

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

文档对此没有太多讨论,或者也许我错过了它。

任何帮助将非常感激。

Jos*_* D. 2

所有标准属性都是自动转发的道具。标准属性如defaultValuetype。请注意 React 中属性的驼峰式大小写表示法。

如果它是像 prop 这样的自定义属性someCustomAttribute,则不会直接传递给 DOM。

如果存在适用于样式组件的所有实例的 props ,您可以使用.attrs.

const StyledTextInput = styled.TextInput.attrs(props => ({
  height: props.height
}))`
  // other styles
`
Run Code Online (Sandbox Code Playgroud)