2017-06-01 58 views
0

我在ReactJS中构建了一个简单的应用程序,该应用程序通过调用某个API与JSON数组一起工作。然后我在表中填充数组的结果。我现在想要的是点击表格中的任何一行,并将这些值传递给其他组件。我想知道如何使用onClick获取行信息。试图获取有关单击表上行的行信息reactJS

这是我的代码。

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; 

回答

1

通过国家元素的索引和检索值状态数组。此外它不需要在映射之前将状态复制到另一个变量,您可以使用状态本身执行它

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); 
} 
+0

忘了提及。当我将onClick属性添加到该行时,出现此错误。 'TypeError:无法在Array.map(native)'http:// localhost:8070/dist/index.js:2558:65'处未定义属性'fetchAccountDetails'' –

+0

没有看到它,这是一个绑定问题,在地图上使用箭头功能,更新了代码 –

+0

谢谢。我已添加这些更改。现在,当我刷新页面时,在控制台中,打印所有值时不点击行。 'onClick'似乎不起作用。另外我在'onClick'中使用fetchAccountDetails时添加了索引参数 –

0

提取采用了

fetchAccountDetails (event) { 

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

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

现在,你有你的数据集状态,你可以使用任何你想要哟