I am trying to apply click listener on list item in material-ui
in reactjs
. I have set onTouchTap
for it as below:
_renderTodos() {
return this.state.todos.map(event => {
return (
<ListItem
primaryText={event.text}
key={event.id}
style={{ width: "100%", textAlign: "center" }}
onTouchTap={this._handleListItemClick(event)}
/>
);
});
}
_handleListItemClick(item) {
console.log("Clicked!!");
}
render() {
return (
<MuiThemeProvider>
<div>
<AppBarTest />
<FloatingActionButton
style={styles.fab}
backgroundColor={colors.blue_color}
onTouchTap={this.handleOpen}
>
<ContentAdd />
</FloatingActionButton>
<Dialog
open={this.state.open}
onRequestClose={this.handleClose}
title={strings.dialog_create_note_title}
>
<TextField
name="notetext"
hintText="Note"
style={{ width: "48%", float: "left", height: 48 }}
defaultValue={this.state.noteVal}
onChange={this.handleChange}
onKeyPress={ev => {
if (ev.key === "Enter") {
this.handleCreateNote();
ev.preventDefault();
}
}}
/>
<div
style={{
width: "4%",
height: "1",
float: "left",
visibility: "hidden"
}}
/>
<FlatButton
label={strings.create_note}
style={{ width: "48%", height: 48, float: "left" }}
onTouchTap={this.handleCreateNote}
/>
</Dialog>
<List style={{ margin: 8 }}>
{this._renderTodos()}
</List>
</div>
</MuiThemeProvider>
);
}
}
When I click on ListItem
then it does not trigger _handleListItemClick
method, instead when I click on any other component like FlatButton
and FloatingActionButton
then it triggers and print a message on console which I have in _handleListItemClick
.
Can anyone help me what wrong I am doing ?
You need to assign a function
to onTouchTap
event and that function
will get called whenever you clicked on that item, but you are assigning a value by calling that function
(you don't need to call that function), remove ()
.
Write it like this by using arrow function
:
<ListItem
primaryText={event.text}
key={event.id}
style={{ width: "100%", textAlign: "center" }}
onTouchTap={(event) => this._handleListItemClick(event)}
/>
Or another way:
<ListItem
primaryText={event.text}
key={event.id}
style={{ width: "100%", textAlign: "center" }}
onTouchTap={this._handleListItemClick.bind(this)}
/>
_handleListItemClick
function:
_handleListItemClick(event){
console.log('clicked');
}
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.