我正在尝试通过以下方式加载字体,以便当您按下按钮时,您的字体就会加载。当我将 if 语句放入渲染部分时,我收到一条错误消息: RawText“if (fontLoaded=="true")”必须包装在显式文本组件中。请帮我解决这个问题,我很困惑。
我对 native react 很陌生,所以这可能是一个非常基本的问题,很抱歉。
我的代码如下:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, TextInput, ScrollView, TouchableHighlight, Button } from 'react-native';
import { Font } from 'expo';
var fontLoaded = false;
export default class App extends React.Component {
componentDidMount() {
Expo.Font.loadAsync({
'Cabin-Regular-TTF': require('./Cabin-Regular-TTF.ttf'),
});
}
constructor(props) {
super(props);
this.state = { postInput: ""}
}
render() {
return (
<View style={styles.container}>
<View style={{width: 1, height: 30, backgroundColor: '#e8e8e8'}} />
<Button
onPress={this.setState({ fontLoaded: true })}
title="Press Me To Load the App After 15 Seconds!"
color="#841584"
accessibilityLabel="Wait 15 seconds and then press me to load the font!"
/>
if (fontLoaded=="true") {
<View style={styles.container}>
<Text style={{ fontFamily: 'Cabin-Regular-TTF', fontSize: 16 }}>
Whats on your mind? Create a post!
</Text>
<TextInput>
tyle={{height:40, width: 320, borderColor: '#303030', borderWidth: 1}}
onChangeText={(postInput)=>this.setState({postInput})}
value={this.state.postInput}
</TextInput>
<ScrollView>
<View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
<View style={{width: 300, height: 250, backgroundColor: '#1daff1'}} />
<View style={{width: 300, height: 40, backgroundColor: '#147aa8'}} />
<View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
<View style={{width: 300, height: 250, backgroundColor: '#1daff1'}} />
<View style={{width: 300, height: 40, backgroundColor: '#147aa8'}} />
<View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
<View style={{width: 300, height: 250, backgroundColor: '#1daff1'}} />
<View style={{width: 300, height: 40, backgroundColor: '#147aa8'}} />
<View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
<View style={{width: 300, height: 250, backgroundColor: '#1daff1'}} />
<View style={{width: 300, height: 40, backgroundColor: '#147aa8'}} />
<View style={{width: 1, height: 6, backgroundColor: '#e8e8e8'}} />
</ScrollView>
</View>
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#e8e8e8',
alignItems: 'center',
justifyContent: 'center',
},
});
最佳答案
问题是您试图在 html 中使用原始 javascript。您不能在 render()
函数内使用常规 if
语句,但可以使用内联条件语句,如下所示:
{isTrue ? (<div>True</div>) : (<div>False</div>)}
了解更多信息here
在你的情况下,它会是这样的:
render() {
return (
{/*your code as usual*/}
{fontLoaded ? (
<View style={styles.container}>
{/*your code as usual*/}
</View>) :
null}
关于javascript - 在 native react 中,当我在渲染部分放置 if 语句检查变量的值时,出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46657981/