Javascript 在react native中显示按钮和文本

Javascript 在react native中显示按钮和文本,javascript,react-native,expo,Javascript,React Native,Expo,我尝试在react native today中编写代码,并尝试编写一个带有按钮和文本的程序,该文本会随着每次按下而改变: import { Text, View, StyleSheet, TouchableOpacity, Button, TextInput } from 'react-native'; import Constants from 'expo-constants'; export default () => { const onButton = () => {

我尝试在react native today中编写代码,并尝试编写一个带有按钮和文本的程序,该文本会随着每次按下而改变:

import { Text, View, StyleSheet, TouchableOpacity, Button, TextInput } from 'react-native';
import Constants from 'expo-constants';


export default () => {

const onButton = () =>
{
  myResult(10);
}

return (
  <Text>Hello World</Text>  

  <Button
  onPress={onButton}
  title="Click Here to calculate"
  color="black"
  />
)
}
从'react native'导入{Text,View,StyleSheet,touchablepacity,Button,TextInput};
从“expo常量”导入常量;
导出默认值()=>{
const onButton=()=>
{
结果(10);
}
返回(
你好,世界
)
}
它给了我这个错误:

Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?
解析错误:相邻的JSX元素必须包装在封闭标记中。你想要一个JSX片段吗。。。?
如果我这样评论text类或button类:
//你好,世界
另一个班可以


有什么建议吗?

您不能这样渲染多个组件。正如错误消息所说,您必须将它们包装在一个封闭的标记中

<View>
    <Text>Hello World</Text>  

    <Button
      onPress={onButton}
      title="Click Here to calculate"
      color="black"
    />
</View>

你好,世界

您将返回两个组件,在react中,您必须只返回一个组件,因此您的代码可以用两种方式包装:

<View>
    <Text>Hello World</Text>  

    <Button
      onPress={onButton}
      title="Click Here to calculate"
      color="black"
    />
</View>

最好的选择是将其包装在
标签中,如其他两个答案中所述


这是一个有趣的解决方案,您甚至可以返回一个数组

例如:

return [
        <Text>Hello World</Text>, 
        <Button 
           onPress={onButton}
           title="Click Here to calculate"
           color="black" 
        />
];
返回[
你好,世界,
];

您引用的错误消息非常明确地说明了问题所在以及如何解决问题。除了下面的两个答案之外,我认为您还需要将
onPress={onButton}
替换为
onPress={()=>{onButton()}}
,否则您的函数甚至会在单击按钮之前被调用。
return [
        <Text>Hello World</Text>, 
        <Button 
           onPress={onButton}
           title="Click Here to calculate"
           color="black" 
        />
];