【问题标题】:Unable to call react component class from another component class [duplicate]无法从另一个组件类调用反应组件类[重复]
【发布时间】:2016-10-29 22:54:10
【问题描述】:

我是 reactjs 和 javascript 的新手。我正在尝试创建一个非常基本的登录和注册表单。当客户输入电子邮件和密码并单击“注册”时,该表格应将他带到下一个表格 - 这是联系信息表格。但是我的页面刷新并带我回到原始屏幕而不是联系信息屏幕。这是登录和联系信息的代码-

import React from 'react';
import {render} from 'react-dom';
import { ContactInfo } from './ContactInfo.jsx'

var App = React.createClass ({
handleClick: function(){
    <ContactInfo new="new"/>;
},
render: function() {
return (<div>
<h1>Login</h1>

    <form>
    Email:  <input type="text" name="email" method="get" />
    <br />      
    <br />
    Password:  <input type="password" name="pwd" />
    <br />
    <a href=""><i>forgot password?</i></a>
    <br /><br />
    <button>Login</button>
    <button onClick={this.handleClick}>Register</button>
    </form>
     </div>);
}
});

render(<App />, document.getElementById('app'));

和联系信息:

import React from 'react';

var ContactInfo = React.createClass({

render: function(){
return(
<div>
 <form>
    Name:  <input type="text"/>
    <br />      
    <br />
    Phone:  <input type="text"/>
    <br />
    Address:
    Street <input type = "text" />
    <br />
    City    <input type = "text" />
    <br />
    State <input type = "text" /><p>  </p>zip <input type = "text" />
    <br />
    Country <input type = "text" />
    <br /><br />
    <button>Continue</button>
    </form>
</div>);
}

});

export default ContactInfo;

【问题讨论】:

  • 好的。所以我理解它的方式是 - 当有人点击注册按钮时,我的 handleClick 处理程序函数“调用”ContactInfo。通话后,ContactInfo 类应呈现相关表单。对?任何更正都非常感谢!

标签: javascript reactjs login


【解决方案1】:

您的 handleClick 方法行为不正常。现在它包含一些完全没有做任何事情的jsx。

你应该做的是

  1. 有一个父组件来处理你在哪个视图上
  2. 登录表单和 ContactInfo 是各自独立的组件
  3. 父级跟踪其状态应呈现的表单
  4. onClick 应该更新该状态,这将导致父级重新渲染并更新它正在渲染的表单

太棒了

类似的东西

React.createClass ({
  getInitialState: function () {
    return {
      currentForm: "login"
    };
  },

  handleLoginFormClick: function () {
    this.setState({currentForm: "contact"});
  },

  renderLoginForm: function () { 
    return (
      <LoginForm onClick={this.handleLoginFormClick} />
    );
  },

  renderContactForm: function () { 
    return (
      <ContactForm />
    );
  },
  render: function () {
    switch (this.state.currentForm) {
      case "login":
        return this.renderLoginForm();
      case "contact":
        return this.renderContactForm();
    }
  }
});

【讨论】:

  • 好的,所以我发现我没有在我的按钮上设置 type 和 id 属性。现在修好了!!
  • 很抱歉,我不小心删除了您的回复。
  • 哈哈哈我想你删除了你的问题所以我删除了我的回复?我不知道。 ? 无论如何,很高兴它现在对你有用!
猜你喜欢
  • 2017-08-20
  • 1970-01-01
  • 2023-03-17
  • 2019-03-29
  • 2019-10-09
  • 1970-01-01
  • 2019-03-08
  • 2022-01-02
  • 1970-01-01
相关资源
最近更新 更多