【问题标题】:Instantiating a Component in React在 React 中实例化组件
【发布时间】:2016-11-27 00:25:46
【问题描述】:

我正在制作一个向导表单,但我无法加载第一个名为 tableResults 的组件。我有一个称为 step 的状态,它根据组件而变化。当前步骤的初始状态设置为 1。当状态为 1 时,如何让 tableResults 显示?

Step1.js sn-p

import tableResults from './tableResults';

class Step1 extends Component {
    constructor(props) {
      super(props);
     this.state = {
      step: 1
    }
  }


render() {
  const {
    handleSubmit,
    previousPage,
    step
  } = this.props;


    return (  
      <form onSubmit={handleSubmit}>

        <div className="step-container">

          {step === 1 && <tableResults/>}
          </div>
      </form>
    );
  }
}

表格片段:

import React, { Component, PropTypes } from 'react'

class tableResults extends Component {
  constructor(props) {
    super(props)
    }

  render() {

    return (  
      <div>
        This is the table
      </div>
      );
  }
}

【问题讨论】:

    标签: reactjs components state


    【解决方案1】:

    您从 props 中获取状态,但您应该从状态中获取它,如下所示:

    import tableResults from './tableResults';
    
    class Step1 extends Component {
        constructor(props) {
          super(props);
         this.state = {
          step: 1
        }
      }
    
    
    render() {
      const {
        handleSubmit,
        previousPage,
        step
      } = this.props;
    
    
        return (  
          <form onSubmit={handleSubmit}>
    
            <div className="step-container">
    
              {this.state.step === 1 && <tableResults/>}
              </div>
          </form>
        );
      }
    }

    【讨论】:

    • 谢谢!我认为这成功了,但是,我的 tableresults 组件没有出现。代码是否正确?
    • 以大写字母命名您的组件。那么它应该可以工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2019-03-07
    • 2019-04-13
    相关资源
    最近更新 更多