繁体   English   中英

尝试获取有关在reactJS中单击表上的行的行信息

[英]Trying to get the row information on clicking a row on table in reactJS

我在ReactJS中构建了一个简单的应用程序,该应用程序通过调用某个API与JSON数组一起使用。 然后,我在表中填充数组的结果。 我现在想要的是单击表中的任何行,并将那些值传递到其他组件中。 我想知道如何使用onClick获得行信息。

这是我的代码。

class ParentComponent extends Component {

constructor(props){
  super(props);
  this.state = {data: []};
}


componentDidMount() {
   fetch('http://hostname:xxxx/yyyy/zzzz')
  .then(function(response) {
   return response.json();
  })
  .then(items=>this.setState({data: items}));
 } 

fetchAccountDetails () {

}

render(){
var newdata = this.state.data;

        return (
            <table className="m-table">
                <thead>
                        <tr>
                            <th>AccountName</th>
                            <th>ContractValue</th>
                        </tr>
                    </thead>
                <tbody>
                    {
                      newdata.map(function(account, index){
                        return (
                          <tr key={index} data-item={account}  onClick={this.fetchAccountDetails()}>
                            <td data-title="Account">{account.accountname}</td>
                            <td data-title="Value">{account.negotiatedcontractvalue}</td>
                          </tr>
                              )
                            }
                          )
                    }
                </tbody>
              </table>
            );
        }
    }

export default ParentComponent;

传递状态元素的索引并从状态数组中检索。 同样,在映射之前不需要将状态复制到另一个变量,您可以使用状态本身来完成

 render(){

    return (
        <table className="m-table">
            <thead>
                    <tr>
                        <th>AccountName</th>
                        <th>ContractValue</th>
                    </tr>
                </thead>
            <tbody>
                {
                  this.state.data.map((account, index) => {
                    return (
                      <tr key={index} data-item={account}  onClick={() => this.fetchAccountDetails(index)}>
                        <td data-title="Account">{account.accountname}</td>
                        <td data-title="Value">{account.negotiatedcontractvalue}</td>
                      </tr>
                          )
                        }
                      )
                }
            </tbody>
          </table>
        );
    }
}

fetchAccountDetails(index) {
    var values = this.state.data[index];
    console.log(values);
}

使用获取值

fetchAccountDetails (event) {

Account:event.target.value
this.getData(Account);
}

getData: function(var account)
this.setState({
        state: account
    });

现在您已经将数据设置为状态,并且可以在任何需要的地方使用它了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM