【问题标题】:react-native with styled-components parent propreact-native with styled-components parent prop
【发布时间】: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


【解决方案1】:

如果你想遵循 React 的模式,有一种方法。将相同的道具传递给&lt;second&gt;。

不过,您可以做的是对孩子使用适当的道具,如下所示

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

然后

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

【讨论】:

  • 重点是我在帖子里说的,我不想在每个组件中重复道具,我只是想让孩子们使用父亲的道具。感谢您的回复。
【解决方案2】:

如果您真的需要这种行为,您可以按如下方式在父母中设置孩子的样式,但是 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;
        }
    `}
`

【讨论】:

    猜你喜欢
    • 2020-01-08
    • 2021-02-19
    • 2021-11-25
    • 2018-10-20
    • 2020-10-19
    • 2019-08-06
    • 2022-09-25
    • 2021-06-04
    • 2018-04-14
    相关资源
    最近更新 更多