我正在使用react native v0.49,我想在两个组件之间使用道具,但是我收到了这个错误
bundling failed: Error: require() must have a single string literal argument
walkThroughtComponent
import React, { Component } from 'react';
import {
View,
Text,
Button
} from 'react-native';
// styles
import { style } from './style';
import { globalStyle } from '../../assets/styles/globalStyle';
// third library
import Swiper from 'react-native-swiper';
// import animations
import LottieAnimation from '../../components/common/LottieAnimation';
saveWelcome = () =>{
// save welcome token after see the welcome slider
}
const Walkthrough = (props) => {
const { wrapper, slide1, slide2, slide3, text } = style;
return (
<Swiper style={ wrapper } showsButtons={true} loop = {false}>
<View style={ slide1 }>
<LottieAnimation name="CheckMark.json"/>
</View>
<View style={ slide2 }>
<Text style={ text }>Beautiful</Text>
</View>
<View style={ slide3 }>
<Text style={ text }>And simple</Text>
<Button title="LOG IN" color='red' onPress={() => console.log("save in asyncStorage")} />
</View>
</Swiper>
);
}
export default Walkthrough;
我要传递道具并在那里使用的组件
import React, {Component} from 'react';
import Animation from 'lottie-react-native';
export default class LottieAnimation extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
this.animation.play();
}
render() {
return (
<Animation
ref={animation => { this.animation = animation; }}
style={{
width: 200,
height: 200,
}}
source={require(`./AnimationsJson/${this.props.name}.json`)}
loop ={ true }
speed = {0.1}
/>
);
}
}
我正在尝试使用this.props.name变量并使用source require的路径,但我真的卡住了,因为这个问题。
答案 0 :(得分:2)
不行。您必须将所有动画“预先要求”到对象中,然后在那里进行引用:
const animations = {
fizz: require('fizz.json'),
buzz: require('buzz.json'),
};
...
<Animation
...
source={animations[this.props.name]}
...
/>
这种方法的好处在于你可以在该对象中定义其他道具,例如:
const animations = {
fizz: {
source: 'fizz.json',
loop: false,
speed: 0.1,
},
}
答案 1 :(得分:1)
您可以将'require'直接设置到子组件中。请查看以下更新的行,
<LottieAnimation name={require("CheckMark.json")} />
<Animation
ref={animation => { this.animation = animation; }}
style={{
width: 200,
height: 200,
}}
source={this.props.name}
loop ={ true }
speed = {0.1}
/>