小编典典

单击React中的按钮时显示组件

reactjs

我是新来的。只有在单击按钮后才如何渲染组件?

就我而言,在单击按钮的情况下,我必须显示一个表,该表显示来自数据库的数据。

我在下面附加了我的代码供您参考,第一个组件是按钮组件,而在下面您可以找到表格的组件。

我也想知道如何在单击按钮时刷新组件而不刷新整个页面。

var Button = React.createClass({
render: function () {
        return (
           <button type="button">Display</button>

            ); }
});

var EmployeeRow = React.createClass({

    render: function () {
        return (
            <tr>
                  <td>{this.props.item.EmployeeID}</td>
                  <td>{this.props.item.FirstName}</td>
                  <td>{this.props.item.LastName}</td>
                  <td>{this.props.item.Gender}</td>                                                   
              </tr>

            );
    }
});

  var EmployeeTable = React.createClass({

      getInitialState: function(){

          return{
              result:[]
          }
      },
      componentWillMount: function(){

          var xhr = new XMLHttpRequest();
          xhr.open('get', this.props.url, true);
          xhr.onload = function () {
              var response = JSON.parse(xhr.responseText);

              this.setState({ result: response });

          }.bind(this);
          xhr.send();
      },
      render: function(){
          var rows = [];
          this.state.result.forEach(function (item) {
              rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
          });
          return (
<Button />
  <table className="table">
     <thead>
         <tr>
            <th>EmployeeID</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Gender</th>               
         </tr>
     </thead>
      <tbody>
          {rows}
      </tbody>
  </table>

  );
  } });

  ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
          document.getElementById('grid'))

阅读 305

收藏
2020-07-22

共1个答案

小编典典

我已经设置了一个沙箱来展示如何执行此操作。

在本质上:

  1. 初始化状态,并将布尔值设置为 false
  2. 根据此布尔值有条件地渲染组件;所以最初该组件现在将显示在DOM上
  3. 在某些动作(onClick)上,setStatetrue
  4. 自从状态更改以来,该组件将重新呈现,并且现在将显示隐藏的组件(因为布尔值已设置为true
2020-07-22