I am trying to render React components using loop, Basically its link tag having on click function with value.
<p><a href="#" key={i} onClick={() => this.decreaseCount(i)} >delete</a></p>
where i is the index of the for loop. The problem is, instead of getting i's value inside this.decreaseCount(i) I am getting length of array. However I am getting correct index with key={i}
Need help!
That should work, try to use this (another way):
<p><a href="#" key={i} onClick={this.decreaseCount.bind(this,i)} >delete</a></p>
Check this example, you way will also work:
class App extends React.Component{ a(i){ console.log(i); } render(){ return ( <div> { [1,2,3].map(i => <p onClick={ () => this.a(i)} > {i} </p>) } </div> ) } } ReactDOM.render(<App/>,document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='app'/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.