如何在不使用JSX的情况下在React Native中创建组件?

And*_*ltz 19 javascript reactjs react-jsx react-native

使用React Native的规范方法显然是使用JSX:

render: function() {
  var movie = MOCKED_MOVIES_DATA[0];
  return (
    <View style={styles.container}>
      <Text>{movie.title}</Text>
      <Text>{movie.year}</Text>
      <Image source={{uri: movie.posters.thumbnail}} />
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

我怎么才使用JavaScript?通常在正常的React中,它React.createElement('div')可以作为JSX的替代品,但在尝试运行我的iOS React Native应用程序时,我收到错误"null不是函数".

Dan*_*ker 20

我试着联系打包器,它说它在端口8081上监听并且还说它在index.ios.bundle运行时收到请求.

所以我把它放在我的浏览器中:http:// localhost:8081/index.ios.bundle

在返回的包中,我发现:

var wazoo = React.createClass({displayName: "wazoo",
  render: function() {
    return (
        React.createElement(View, {style: styles.container}, 
          React.createElement(ScrollView, null, 
            React.createElement(View, null, 
                React.createElement(Text, {style: styles.welcome}, 
                  "Wazoo"
                ), 
Run Code Online (Sandbox Code Playgroud)

等等.所以它看起来像View,ScrollView等等.就像组件定义为网络通常反应,上面的代码是JS相当于JSX.


Sav*_*ipt 14

Daniel Earwicker的解决方案是正确的,但我们可以使用Factories使其更具可读性:

var View       = React.createFactory(React.View);
var ScrollView = React.createFactory(React.ScrollView);
var Text       = React.createFactory(React.Text);

var wazoo = React.createClass({displayName: "wazoo",
  render: function() {

    return View({style: styles.container}, 
      ScrollView(null, 
        View(null, 
          Text({style: styles.welcome}, 
            "Wazoo"
          )
        )
      )
    );


  }
});
Run Code Online (Sandbox Code Playgroud)