![](/img/trans.png)
[英]How to change the menu item's color of sidebar when we click on it with Material-UI in React?
[英]How to set click listener on list item in material ui in react js
我正在嘗試在reactjs
material-ui
列表項上應用單擊偵聽reactjs
。 我為它設置了onTouchTap
,如下所示:
_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>
);
}
}
當我單擊ListItem
它不會觸發_handleListItemClick
方法,而是當我單擊任何其他組件(如FlatButton
和FloatingActionButton
它會觸發並在控制台上打印一條消息,該消息在_handleListItemClick
。
誰能幫我我在做什么錯?
您需要為onTouchTap
事件分配一個function
,只要單擊該項目,該function
就會被調用,但是您是通過調用該function
來分配值的(不需要調用該函數),請刪除()
。
使用arrow function
將其編寫為:
<ListItem
primaryText={event.text}
key={event.id}
style={{ width: "100%", textAlign: "center" }}
onTouchTap={(event) => this._handleListItemClick(event)}
/>
或另一種方式:
<ListItem
primaryText={event.text}
key={event.id}
style={{ width: "100%", textAlign: "center" }}
onTouchTap={this._handleListItemClick.bind(this)}
/>
_handleListItemClick
函數:
_handleListItemClick(event){
console.log('clicked');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.