使用styled-components(react-native)和动画

20
我正在经历一个错误,它报告如下(通过iOS测试):
无法读取null的getScrollableNode属性
当尝试使用react-native的Animatedstyled-components样式工具来处理react和react-native时。
这是我创建的<Logo />组件的示例:
import React from 'react';
import { Image, Dimensions } from 'react-native';
import styled from 'styled-components/native';

const { width } = Dimensions.get('window');
const logoWidth = width - (width * 0.2);
const logoHeight = logoWidth * 0.4516;

const SLogoImage = styled(Image)`
  width: ${logoWidth};
  height: ${logoHeight};
`;

const Logo = ({ ...rest }) => (
  <SLogoImage
    source={require('../assets/logo.png')}
    {...rest}
  />
);

export default Logo;

我随后将此组件导入到我的场景之一中,我想对其应用动画:

import React from 'react';
import { View, Animated } from 'react-native';
import Logo from '../components/Logo';

const ALogo = Animated.createAnimatedComponent(Logo);

class HomeScene extends Component {
  state = {
    fadeAnim: new Animated.Value(0)
  }

  componentDidMount() {
    Animated.timing(
      this.state.fadeAnim,
      { toValue: 1 }
    ).start()
  }

  render() {
    <View>
      <ALogo style={{ opacity: this.state.fadeAnim }} />
    </View>

  }
}

export default HomeScene;

这导致了上述错误,尝试通过谷歌搜索并未找到任何解释。如有必要,请随时请求进一步的细节。

相关 GitHub 问题: https://github.com/styled-components/styled-components/issues/341

1个回答

19

这个问题实际上与styled-components无关。相反,它是一个react-native问题

解决此问题的方法是使用class而不是无状态组件。

class Logo extends React.Component {
  render () {
    return (
      <SLogoImage
        source={require('./geofence.gif')}
        {...this.props}
      />
    )
  }
}

这里有一个Github Repo,可以看到它是如何工作的。如果有人想要重现它,请取消注释14-21行以查看错误。

我认为问题出在Animated 试图将ref附加到一个无状态组件上。而无状态组件无法拥有引用(refs)


2
非常好的发现,谢谢 :) 我将在20小时内颁发奖励。 - Ilja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接