6

Trying to learn React JS / JSX at the moment and have gotten stuck creating a simple login form:

/**
* @jsx React.DOM
*/

var loginForm = React.createClass({
    getInitialState: function() {
        return {loggedIn : false};
    },
    login : function(event) {
        alert('logging in');
    },
    logout : function(event) {
        alert('logging out');
    },
    render: function() {
        return (
            <div>
                <form /*action={this.server+'/login.php'}*/>
                    <label htmlFor="username">Username:</label>
                    <input type="text" id="username" name="username" />
                    <label htmlFor="password">Password:</label>
                    <input type="password" id="password" name="password" />
                </form>
            </div>
            <div>
                <button onClick={this.login}> Login </button>
                <button onClick={this.logout}> Logout </button>
            </div>
        )
    }



});

React.renderComponent(
  <loginForm />,
  document.body
);

If I remove the <button> tags it works fine but otherwise an error is thrown:

Uncaught Error: Parse Error: Line 27: Unexpected identifier

<button onChange={this.logout}> Logout ... ^

fiddle: http://jsfiddle.net/4TpnG/90/

4

3 回答 3

14

您正在尝试从该函数返回两个 div。在文档中它说:

目前,在一个组件的渲染中,你只能返回一个节点;例如,如果您有要返回的 div 列表,则必须将组件包装在 div、span 或任何其他组件中。

不要忘记 JSX 编译成常规的 js;返回两个函数并没有真正的语法意义。同样,不要将多个孩子放入三元组。

因此,您可以通过将两个根 div 包装在一个 div 中来修复它;或将您的第二个根 div(使用按钮)移动到第一个。

于 2014-05-05T06:49:09.240 回答
1
<div>
    <form /*action={this.server+'/login.php'}*/>
            <label htmlFor="username">Username:</label>
            <input type="text" id="username" name="username" />
            <label htmlFor="password">Password:</label>
            <input type="password" id="password" name="password" />
   </form>
   <div>
      <button onClick={this.login}> Login </button>
      <button onClick={this.logout}> Logout </button>
   </div>
</div>

尝试使用这个,如果你有两个 div/nodes 似乎它不会工作

于 2014-05-05T06:50:58.410 回答
1

你可以做:

return ([
    <div>
        <form /*action={this.server+'/login.php'}*/>
            <label htmlFor="username">Username:</label>
            <input type="text" id="username" name="username" />
            <label htmlFor="password">Password:</label>
            <input type="password" id="password" name="password" />
        </form>
    </div>, // note the comma
    <div>
        <button onClick={this.login}> Login </button>
        <button onClick={this.logout}> Logout </button>
    </div>
]);
于 2016-07-13T14:36:03.240 回答