我正在使用一个简单的演示来学习本地反应,我发现了一件奇怪的事情。
这是我的代码:
export default class App extends Component {
constructor(props) {
super(props)
this.state = {success: false}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js.
{this.state.success} //this line can not be shown
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
我在constructor()
中使用设置状态,但在render()
中无法访问它,当我将success
值设置为字符串或int时,它将显示。
我的代码有什么问题吗?为什么我不能使用布尔值?
您可以访问它,但没有显示任何内容,因为它是布尔值,而不是字符串或数字。
如果你想显示文字"true"或"false",你应该先用toString()
:把它转换成字符串
<Text style={styles.instructions}>
To get started, edit App.js.
{this.state.success.toString()}
</Text>
如果我没记错的话,我读到他们决定不呈现布尔值,以支持更灵活的内联条件。
短路评估就是这样一个例子:
{!this.state.success && <p>Whoops, something went wrong!</p>}
如果success
为true,则不会呈现上面的消息。然而,在vanillaJS中,这将返回字符串文本"false"——当您想要呈现一些东西或什么都不呈现时,这并不理想。
想象一下,如果您呈现某个对象方法(即indexOf()
、map()
等)的返回值,并对undefined、null和其他错误值的字符串文本进行react呈现,会有多烦人。这种情况不会发生;相反,React什么也不渲染。
官方文档中的更多信息请点击此处:
false
、null
、undefined
和true
是有效的子级。它们根本不会渲染。这些JSX表达式都将呈现为相同的东西: