2017-09-25 61 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

相關問題