【发布时间】: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