19

使用 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>
  );
}

我将如何仅使用 JavaScript 来做到这一点?通常在正常的 React 中,React.createElement('div')它可以作为 JSX 的替代品,但是在尝试运行我的 iOS React Native 应用程序时,我得到一个错误“null is not a function”。

4

3 回答 3

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

等等。所以看起来View, ScrollViewetc. 就像 Web React 中通常定义的组件一样,上面的代码是 JS 等价于 JSX。

于 2015-03-26T20:53:03.190 回答
16

Daniel Earwicker's solution is correct, but we can use Factories to make it more readable:

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


  }
});
于 2015-04-22T15:56:15.067 回答
0

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:

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.

于 2017-03-14T18:08:32.290 回答