【发布时间】:2018-03-06 04:53:17
【问题描述】:
我在我的 react-native 项目中使用 styled-components,我想知道如何从子元素中获取 parent prop .. 这是一个示例,我有 2 个 styled-components
const First = styled.View`
display: flex;
width: 50px;
height: 50px;
background-color: ${props => props.selected ? 'blue' : 'red'};
`
const Second = styled.Text`
// here I want to check if First has the selected prop.
color: ${props => props.selected ? '#fff' : '#000'};
`
还有我自己的 React 组件
const Test = () = (
<First selected>
<Second>Test</Second>
</First>
)
现在我如何检查Seconds 父亲(即First)是否有selected 属性?
我知道如果我将选定的 attr 提供给Second 它将起作用,但这不是我想要实现的......必须有一种方法,因为它们是嵌套的,我试图控制台日志和道具 arg 但我不能'在子对象返回的对象中找不到父值。
谢谢
【问题讨论】:
-
将父道具作为新道具传递给孩子..
-
@John,这就是我不想使用相同的道具两次,我想从父母那里得到它
-
当您作为道具传递给孩子时,您是从父母本身获得的。这是最简单的方法。但是,不建议在孩子中访问父实例。检查这个stackoverflow.com/a/34257785/1066839
-
@John,谢谢这正是我要找的,我有点确定
styled-components的“帮手”或其他东西会在这种情况下有所帮助。
标签: react-native styled-components