我想加载一个本地图像,但是使用require()方法,它总是给我错误,在这种情况下,如何在require中传递this.props.image。
我的代码:
Card.js
我尝试过:
class Card extends Component {
render() {
return (
<View>
<Image source={require(this.props.image)} style={styles.imageBox}/>
</View>
);
}
}
这:
class Card extends Component {
render() {
return (
<View>
<Image source={require({this.props.image})} style={styles.imageBox}/>
</View>
);
}
}
App.js
class App extends Component {
static navigationOptions = { header: null }
render() {
return (
<Card
image='./img/demo.jpg'
/>
);
}
}
答案 0 :(得分:2)
如ReactNative
文档中的Image所说
// GOOD
<Image source={require('./my-icon.png')} />;
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;
// GOOD
var icon = this.props.active
? require('./my-icon-active.png')
: require('./my-icon-inactive.png');
<Image source={icon} />;
所以试试看 首先在App.js中加载图片
class App extends Component {
static navigationOptions = { header: null }
render() {
return (
<Card
image={require('./img/demo.jpg')}
/>
);
}
}
Card.js和您一样。
答案 1 :(得分:0)
您必须首先导入图像并使用它。
App.js
import image from './img/demo.jpg';
class App extends Component {
static navigationOptions = { header: null }
render() {
return (
<Card
image={image}
/>
);
}
}
card.js
class Card extends Component {
render() {
return (
<View>
<Image source={this.props.image} style={styles.imageBox}/>
</View>
);
}
}
OR
App.js
class App extends Component {
static navigationOptions = { header: null }
render() {
return (
<Card
image={'logo.png'}
/>
);
}
}
card.js
class Card extends Component {
render() {
return (
<View>
<img src={require(`./img/${this.props.image}`)} alt='img' style={styles.imageBox}/>
</View>
);
}
}