簡體   English   中英

如何在React JS中的材料UI中的列表項上設置點擊監聽器

[英]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方法,而是當我單擊任何其他組件(如FlatButtonFloatingActionButton它會觸發並在控制台上打印一條消息,該消息在_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM