简体   繁体   English

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

[英]How do I make components in React Native without using JSX?

The canonical way of using React Native is apparently with JSX: 使用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>
  );
}

How would I do this using JavaScript only? 我怎么才使用JavaScript? Typically in normal React, React.createElement('div') would work as an alternative to JSX, but I get an error "null is not a function" when trying to run my iOS React Native app. 通常在正常的React中, React.createElement('div')可以作为JSX的替代品,但在尝试运行我的iOS React Native应用程序时,我收到错误“null不是函数”。

I tried contacting the packager, which says it listens on port 8081 and also says that it is getting requests for index.ios.bundle as it runs. 我尝试联系打包器,它说它在端口8081上侦听并且还说它在运行时收到了index.ios.bundle请求。

So I put this in my browser: http://localhost:8081/index.ios.bundle 所以我把它放在我的浏览器中: http:// localhost:8081 / index.ios.bundle

In the returned bundle, I found: 在返回的包中,我发现:

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"
                ), 

And so on. 等等。 So it looks like View , ScrollView etc. are just like components as defined as usual in Web React, and the above code is the JS equivalent to the JSX. 所以它看起来像ViewScrollView等就像Web React中通常定义的组件一样,上面的代码是JS等同于JSX。

Daniel Earwicker's solution is correct, but we can use Factories to make it more readable: 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"
          )
        )
      )
    );


  }
});

I know it's been a while since the original question but, in case someone else is interested, you could check the library we made at Uqbar: 我知道自原始问题已经有一段时间了,但是,如果其他人感兴趣,你可以查看我们在Uqbar制作的图书馆:

https://www.npmjs.com/package/njsx https://www.npmjs.com/package/njsx

It's quite easy to use and provides a cleaner interface than the React out-of-the-box interface. 它非常易于使用,并提供比React开箱即用界面更清晰的界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM