【问题标题】:react-spring single-component mount/unmount revealsreact-spring 单组件安装/卸载显示
【发布时间】:2019-04-13 04:44:41
【问题描述】:

我正在尝试使用 React-spring 安装/卸载组件时创建动画:

    import { Transition, animated } from 'react-spring'
    ...

    export class CompName extends PureComponent<CompNamePropsType> {
      static defaultProps = {
        isExpanded: false,
      }

      render() {
        const {
          isExpanded,
          ...props
        } = this.props

    return (
      <section className={styles.block} {...props}>
        <Transition
          from={{ opacity: 0 }}
          enter={{ opacity: 1 }}
          leave={{ opacity: 0 }}>
        {isExpanded && (style => (
           <animated.div style={{ ...style, background: "orange" }}>
             <AnotherComp />
           </animated.div>
        ))}
       </Transition>
      </section>
    )
  }
}

但这只是行不通,我收到错误children is not a function。我做错了什么,如何使用 react-spring 包装器在组件挂载/卸载上创建动画?

【问题讨论】:

  • 如果isExpanded 是假的,它会作为children 道具返回给Transition 组件,这似乎需要一个渲染道具,在这种情况下你正确地返回了isExpanded 是真的.当isExpanded 为假时,您可以使用三元运算符重构它并返回某种 noop 函数。
  • @adz5A 当 isExpanded 为 'true' 时错误为 'TypeError: child is not a function',如果它为 'false' - ' TypeError: _children is not a function'
  • 这是因为您的 sn-p 中children 的签名不正确。它是一个返回函数的函数:item =&gt; props =&gt; reactElement。见react-spring.surge.sh/transition。您的示例缺少 items 道具和 children 道具的正确签名。

标签: reactjs jsx react-spring


【解决方案1】:

正确的做法是:

<Transition items={isExpanded} native from enter leave>
  {isExpanded => isExpanded && (props => <animated.div style={props} />)
</Transition>

里面的物品可以是一个单独的物品,就像你的情况一样,然后对出来的物品进行处理。原因是转换会保留它,即使实际状态发生变化,它仍然可以安全地将元素转换到“旧”状态。

这里解释了api:react-spring.io/docs/props/transition

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 2018-08-07
    • 2016-01-14
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多