javascript React JS 显示点击的表格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29567550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:44:25  来源:igfitidea点击:

React JS display clicked table row

javascriptreactjs

提问by Lee Marsden

I am currently trying to learn react by building a simple app that works with a JSON array by calling a certain API. I would then like to show the results of the array in a table and have the ability to click one of the rows and get the data from that row to update another part of the page.

我目前正在尝试通过调用某个 API 构建一个使用 JSON 数组的简单应用程序来学习 React。然后我想在表格中显示数组的结果,并能够单击其中一行并从该行获取数据以更新页面的另一部分。

I have successfully called the API and am showing the correct data in the table but I am struggling to figure out how to show the data after the click in another part of the page. I created a click handler event and can log information to the console but cant figure out how I would show this data on the page for the relevant row that is clicked.

我已成功调用 API 并在表中显示正确的数据,但我正在努力弄清楚如何在页面的另一部分单击后显示数据。我创建了一个点击处理程序事件,可以将信息记录到控制台,但无法弄清楚如何在页面上为点击的相关行显示这些数据。

So I currently have this in my page:

所以我目前在我的页面中有这个:

<div class="container"></div>

<script type="text/jsx">

    var ShowData = React.createClass({

          getInitialState: function() {
            return { data: [] };
          },

          componentDidMount: function() {
            $.get(this.props.source, function(data) {
              if (this.isMounted()) {
                this.setState({
                    data: data
                });
              }
            }.bind(this));
          },

          handleClick: function(i) {
            console.log('You clicked: ' + this.state.data[i].event + this.state.data[i].name);
          },

          render: function() {
            var self = this;
            return (
                <table className="m-table">
                    <thead>
                            <tr>
                                <th>Event</th>
                                <th>Name</th>
                            </tr>
                        </thead>
                    <tbody>
                    {this.state.data.map(function(type, i){
                   return (
                        <tr>
                            <td title="Type" onClick={self.handleClick.bind(this, i)} key={i}>{type.event}</td>
                            <td title="Type">{type.name}</td>
                        </tr>
                    )
                })}

                        </tbody>
                    </table>
            );
          }

        });

  React.render(
          <ShowData source="url of api" />,
          document.getElementById('container')
        );

</script>

Below this script is another container that I would like to show the results when the table row is clicked.

在此脚本下方是另一个容器,我希望在单击表行时显示结果。

So to summarize, I want to display the data from the API call in a table, upon clicking on one of the table rows I want to take the table row data and format it in another container on the page.

总而言之,我想在表中显示来自 API 调用的数据,在单击表行之一时,我想获取表行数据并将其格式化到页面上的另一个容器中。

回答by Markus-ipse

I'd move both the table-component and the display area-component into a parent component that has the responsibility of managing state. The parent component will pass a callback for handling row clicks down to the table, something along the lines of the below edits to your code example. (Heads-up: haven't slept in the past 40+ hours when writing this, due to travel..)

我会将表格组件和显示区域组件移动到一个负责管理状态的父组件中。父组件会将用于处理行点击的回调传递给表格,类似于以下对您的代码示例进行的编辑。(注意:在写这篇文章时,过去 40 多个小时没有睡觉,由于旅行......)

<div class="container"></div>

<script type="text/jsx">

    var TableComponent = React.createClass({   
          handleClick: function(i) {
             this.props.clickHandler(i);
          },

          render: function() {
            var self = this;
            return (
                <table className="m-table">
                    <thead>
                            <tr>
                                <th>Event</th>
                                <th>Name</th>
                            </tr>
                        </thead>
                    <tbody>
                    {this.props.data.map(function(type, i){
                   return (
                        <tr>
                            <td title="Type" onClick={self.handleClick.bind(this, i)} key={i}>{type.event}</td>
                            <td title="Type">{type.name}</td>
                        </tr>
                    )
                })}

                        </tbody>
                    </table>
            );
          }

        });

  var DetailsArea = React.createClass({
      render: function() {
          var rowDetails = this.props.rowDetails;

          return <div>{rowDetails.name}</div>;
      }
  });

  var ParentComponent = React.createClass({
      getInitialState: function() {
          return {data: []};
      },

      componentDidMount: function() {
          $.get(this.props.source, function(data) {
            if (this.isMounted()) {
              this.setState({
                  data: data
              });
            }
          }.bind(this));
       },

       rowClickHandler: function(rowIndex) {
           this.setState({selectedRow: rowIndex});
       },

       render: function() {
           var tableData = this.state.data;
           return (
               <TableComponent data={tableData} clickHandler={rowClickHandler} />
               <DetailsArea rowDetails={tableData[this.state.selectedRow]} />
       }
  });

  React.render(
          <ParentComponent source="url of api" />,
          document.getElementById('container')
        );

</script>