我正在使用樣式組件處理我的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在子對象返回的對象中找到父對象的值。
謝謝
傳遞父道具新道具的孩子.. – John
@約翰,這是我不想使用相同的道具兩次,我想從父母那裏得到它 – greW
當你作爲道具傳遞給孩子時,你從父母本身得到它。這是最簡單的方法。但不建議訪問子實例中的父實例。檢查這個https://stackoverflow.com/a/34257785/1066839 – John