2017-09-25 63 views
1

我正在使用样式组件处理我的react-native项目,我想知道如何从子元素获取父项道具..这里是一个例子, 2风格的组件react-native with styled-components parent prop

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'}; 
` 

和我自己的阵营组件

const Test =() = (
    <First selected> 
    <Second>Test</Second> 
    </First> 
) 

现在我怎么能检查是否Seconds父亲(这是First)具有selected道具? 我知道它会工作,如果我会给选定的attr Second,但它不是我想要实现的...必须有一种方式,因为他们嵌套,我试图控制日志和道具arg,但我不能' t在子对象返回的对象中找到父对象的值。

谢谢

+1

传递父道具新道具的孩子.. – John

+0

@约翰,这是我不想使用相同的道具两次,我想从父母那里得到它 – greW

+2

当你作为道具传递给孩子时,你从父母本身得到它。这是最简单的方法。但不建议访问子实例中的父实例。检查这个https://stackoverflow.com/a/34257785/1066839 – John

回答

0

如果你想关注React的模式,有一种方法。通过相同的道具到<second>

你虽然可以做什么,是使用适当的道具给孩子像下面

const Test =() = (
    <First selected> 
    <Second isParentSelected={selected} >Test</Second> 
    </First> 
) 

然后

const Second = styled.Text` 
    color: ${props => props.isParentSelected ? '#fff' : '#000'}; 
` 
+0

关键是正如我在帖子中所说,我不想在每个组件中重复道具,我只是想让孩子们使用父亲的道具。 感谢您的回复。 – greW

相关问题