【问题标题】:ReactJS, Change page content after button onClickReactJS,按钮onClick后更改页面内容
【发布时间】:2017-08-31 13:42:26
【问题描述】:

我在更改页面内容时遇到问题。 我已经尝试了很多互联网提示。

要点:打开页面后,我想看到loadDepartment和一个按钮。如果我单击“emp”按钮。整页内容改为loadEmployees。我需要这个而不刷新页面。

componentDidMount() {
      return this.initializeContent("hie")
}

initializeContent(choose) {
      if(choose == "emp") {
          console.log("page choosed:", choose);
          return this.loadEmployees();
      }
      else if(choose == "hie") {
          console.log("page choosed:", choose);
          return this.loadDepartment();
      }
      else {
          console.log("not found user choice -", choose);
          return (<div>There is a problem with loading of hierarchy pagae</div>)
      }
  }
  
loadDepartment() {
  return (<div>apple</div>)
}
loadEmployees() {
  return (<div>orange</div>)
}
  
render() {
  return (<div>
        {this.componentDidMount()}
        <button className="userReq" data-name="emp" onClick={this.initializeContent.bind(this, "emp")}>blabla</button>
  </div>)
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你需要切换组件的内部状态。 render() 函数是特殊的,返回值被 React 使用,但 loadEmployees() 函数没有相同的特殊状态。这是你应该做的事情:

    var MyComponent = React.createClass({
    
    
          loadDepartment() {
            this.setState({
              view: "department"
            });
          },
          loadEmployees() {
            this.setState({
              view: "employees"
            });
          },
    
          render() {
            if (this.state.view === "employees") return <div>orange</div>;
            if (this.state.view === "department") return <div > apple </div>;
            return (<div>
              <button className = "userReq"
              data-name = "emp"
              onClick = { this.loadEmployees } >blabla </button> 
              </div>)
            }
          });

    无论何时调用 setState(),组件都会自动重新渲染,它会使用 this.state 的新值来确定要渲染的内容。

    【讨论】:

    • 谢谢,但控制台有错误。 “hierarchy.js:144 Uncaught TypeError: Cannot read property 'view' of null” - 问题是,这段代码在更大的项目中,我只给你展示了一部分。因为loaddep和loademp中没有橙子和苹果。但它们充满了另一个代码。我得到了,你写给我的,可能我没有机会解决这个问题。我是前端开发人员,只是在这部分提供帮助。
    • sn-p 不打算运行(我只是复制了你的并改进了它)。重点是让您阅读代码了解技术 - 在 onClick 处理程序中使用 setState() 来更改组件的内部状态,然后在 render() 中您可以打开 this.state 的值。是不是很清楚,还是希望我换一种方式解释?
    • 从您的角度来看是完全清楚的。问题是,我不懂反应的技术。我必须看一些教程。
    • 我用我们的后端编程器解决了这个问题。和你描述的逻辑一样。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多