React native - 无法返回简单的函数?意外的标记?

时间:2017-07-10 20:17:49

标签: javascript ios facebook reactjs react-native

我正在尝试学习React本机,但即使返回一个简单的函数也失败了。我要么得到意外的令牌错误,要么"没有返回有效的反应元素"部署时我的IOS sim出错。

我试图了解如何返回不同的函数,但教程似乎与Facebook上的原始入门页面的语法不同:

http://facebook.github.io/react-native/releases/0.20/

这就是我所拥有的:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

//import AwesomeComponent from "./awesome.js";

export default class SkysReact extends Component {
  render() {
    return this.test();
      // return (<View style={styles.container}>
      //   <Text style={styles.welcome}>
      //     Welcome to Skylars React Native!
      //   </Text>
      //   <Text style={styles.instructions}>
      //     This is a sandbox.
      //   </Text>
      // </View>);
  }
  var test = function() {
    console.log("hello world");
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#000',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#333333'
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('SkysReact', () => SkysReact);

如何在文件中定义不同的func来操作?

3 个答案:

答案 0 :(得分:3)

在ES6函数中定义方法的另一种可能方法:

export default class SkysReact extends Component {
  render () {
    var test = () => {
      console.log("Hello World")
    }

    const test2 = () => {
      return <h1>Hello from the other side</h1>
    }

    return(
      <div>
        {/*// execute test()*/}
        {test()}

        {/*// execute test2()*/}
        {test2()}
        <h1>Hello World</h1>
      </div>
    )
  }
}

答案 1 :(得分:1)

问题在于你的课程。

export default class SkysReact extends Component {
  render() {
    return this.test();
      // return (<View style={styles.container}>
      //   <Text style={styles.welcome}>
      //     Welcome to Skylars React Native!
      //   </Text>
      //   <Text style={styles.instructions}>
      //     This is a sandbox.
      //   </Text>
      // </View>);
  }
  var test = function() {
    console.log("hello world");
  }
}

这不是你如何在其中定义方法。相反,您应该以这种方式定义test方法:

export default class SkysReact extends Component {

  constructor() {
    this.test = this.test.bind(this);
  }

  render() {
    return this.test();
  }

  test() {
    return (
      /* your jsx here */
    );  
  }

}

答案 2 :(得分:0)

React组件应该返回或渲染React元素。 在ReactNative中,有效的React Element至少有一个元素 例如<Text> Hello World </Text>

如果您想要返回多个元素,则将其包装在View内。例如:

<View>
  <Text> Hello World1 </Text>
  <Text> Hello World2 </Text>
<View>

因此,对于您的代码示例,您可以尝试类似这样的内容

render() {
  return (
   <View>
     {this.test()}
   </View>
}

test() {
  console.log("Hello World")
}
相关问题