Material-UI:未调用ListItem onClick

问题描述 投票:0回答:2

我正在使用React和Material-UI。我正在尝试显示列表并在单击列表中的某个项目时调用函数。下面的代码是我的代码的简化版本,但它应该包含有关该问题的所有行。 onClick函数显然从未调用过。我错过了什么?

App.js:

import React, { Component } from 'react';
import './App.css';
import Grid from '@material-ui/core/Grid';
import Map from './Map.js';

class App extends Component {

  render() {

    return (
      <div >
      <Grid container spacing={24}>
        <Grid item xs={3}>
          Column text
        </Grid>
        <Grid item xs={9}>
            <Map/>
        </Grid>

      </Grid>
      </div>

    );
  }
}

export default App;

Map.js:

import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';


class Map extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      sensorsList: {
        isLoaded: false,
        data: null,
      },
    };
  }

  componentDidMount() {
    // retrieve list of sensors
    fetch("https://api-of-things.plenar.io/api/sensors?size=10000")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            sensorsList: {
              isLoaded: true,
              data: Object.keys(result.data).map(key => result.data[key].path),
            }
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            error
          });
        }
      )
  }

  selectSensor(name) {
    console.log(name);
  }

  _renderSensorsList() {
    const {sensorsList} = this.state;

    return sensorsList.isLoaded && (
      <div style={{
        position: 'absolute', 
        zIndex: 1, 
        pointerEvents: 'none', 
        right: 10, 
        top: 10,
        backgroundColor: 'white',
        }}>

      <List component="nav">
        { sensorsList.data.map(key => 
          <ListItem button key={key} onClick={() => this.selectSensor("ciao")} >
            <ListItemText primary={key} />
          </ListItem>
        )}
      </List>

      </div>
    );
  }

  render() {
    const {sensorsList, selectedSensor} = this.state;

    return (
      <div>
        { this._renderSensorsList() }
      </div>
    );
  }
}

export default Map;
reactjs list onclick material-ui listitem
2个回答
0
投票

问题是在你的div风格中你设置pointerEvents: 'none',阻止点击到达DOM事件监听器,删除它,它将工作。

<div style={{
        position: 'absolute', 
        zIndex: 1, 
        pointerEvents: 'none', //<---- remove this line
        right: 10, 
        top: 10,
        backgroundColor: 'white',
}}>

0
投票

试着替换这个

  _renderSensorsList() {

像这样的箭头功能

  _renderSensorsList = () => {
© www.soinside.com 2019 - 2024. All rights reserved.