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

How do I make components in React Native without using 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>
  );
}

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

我尝试联系包装商,它说它在端口 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"
                ), 

等等。所以看起来ViewScrollView等都是Web React中定义的组件,上面的代码是相当于JSX的JS。

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


  }
});

我知道自最初的问题以来已经有一段时间了,但如果其他人有兴趣,您可以查看我们在 Uqbar 创建的库:

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

它非常易于使用,并且提供比 React 开箱即用的界面更简洁的界面。