首页 文章

与样式组件父道具反应原生

提问于
浏览
3

我正在使用我的react-native项目中的样式组件,我想知道如何从子元素中获取父道具..这是一个例子,我有2个样式组件

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但我找不到父母子项返回的对象中的值 .

谢谢

2 回答

  • 0

    如果你想遵循React的模式,有一种方法 . 将同一道具传递给 <second> .

    你能做的就是给孩子使用适当的道具,如下所示

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

    然后

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

    如果您真的需要这种行为,您可以按照以下方式在父母内部设置孩子的样式,但是Matthew的答案是首选方式:

    import styled from "styled-components";
    
    const Second = styled.Text`...`;
    const First = styled.View`
        display: flex;
        width: 50px;
        height: 50px;
        background-color: ${props => props.selected ? 'blue' : 'red'};
    
        ${Second} {
            color: ${props => props.selected ? '#fff' : '#000'};
        }
    `
    

    或者,您可以使用 css 函数将所有新样式包装在块中:

    import styled, {css} from "styled-components";
    
    const Second = styled.Text`
        color: #000
    `;
    
    const First = styled.View`
        display: flex;
        width: 50px;
        height: 50px;
        background-color: red;
    
        ${props => props.selected && css`
            background-color: blue;
            ${Second} {
                color: #fff;
            }
        `}
    `
    

相关问题