简体   繁体   中英

React. List -> ListItem click and send params

Cant understand how i can create click by item in List and sent params. For example if i using this code

    <List>
         {filesList ? (
           filesList.map((item, index) => (
            <ListItem key={index} button onClick={this.setCurrentUrl(index)}>
               <ListItemIcon>
                   <InsertDriveFile/>
               </ListItemIcon>
               <ListItemText primary={item.name} />
            </ListItem>
        ))
    ) : (
            <ListItem>There are no attachement files</ListItem>)}
            <ListItem/>
      </List>

method setCurrentUrl :

setCurrentUrl(index) {
        console.log(index);
    }

i will have output all items in the console when my page is loaded. Why? But if i make something like this:

<ListItem key={index} button onClick={this.setCurrentUrl} value={index}>

and

setCurrentUrl(event) {
        console.log(event);
    }

then console.log(event); will be call only when i click on item in the list. But in this way i dont know how send params to setCurrentUrl

The way you are using

 <ListItem key={index} button onClick={this.setCurrentUrl(index)}>

it is problematic as the function setCurrentUrl will be called as soon as the component is rendered. To make a call to function only when onClick event is triggered, you need to make use of callbacks.

<ListItem key={index} button onClick={() => this.setCurrentUrl(index)}>

Using callback will not call the function while the component is being rendered and would only call the function when the onClick event is triggered.

The reason it happens because you are calling the function. The function will execute immediately after the component is rendered.

 <ListItem key={index} button onClick={this.setCurrentUrl(index)}>

Instead what you should have done is

<ListItem key={index} button onClick={() => this.setCurrentUrl(index)}>

What this will do is, it will assign the function to the onClick handler and will be invoked only when you click the button.

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.

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