【问题标题】:How do Styled Components forward props?Styled Components 如何转发 props?
【发布时间】:2020-06-07 08:35:21
【问题描述】:

我使用 Styled Components 已经有一段时间了,但老实说,我从来没有真正理解它是如何工作的。这就是我的问题所在。

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

以我为例,我正在使用 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>
    );
  }
}

这是我的问题:

  • styled 组件自动拾取道具的情况有哪些?
  • 自动转发哪些道具。
  • 这个道具转发是如何工作的?

文档并没有对此进行太多讨论,或者我可能错过了它。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs react-native styled-components


    【解决方案1】:

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

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

    如果有对样式组件的所有实例真实的道具,您可以使用.attrs

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

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2021-09-19
      • 2020-05-28
      • 2019-02-18
      • 2018-10-29
      • 2018-04-15
      • 2019-03-14
      • 1970-01-01
      • 2020-03-02
      相关资源
      最近更新 更多