React Material UI 下拉菜单不起作用

React Material UI DropDown Menu Doesn't Work

我有一个组件可以基于 URL 构建动态下拉菜单,它是 REST API:

组合组件代码:

export default class Combo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {data: [], value: 0}
    this.handleChange = this.handleChange.bind(this)
  }
  componentDidMount() {
    // Fetch content
  }
  handleChange(event, index, value) {
    this.setState({value: event.target.value});
  }
  render() {
    return (
      <MuiThemeProvider muiTheme={getMuiTheme()}>
        <DropDownMenu style={styles.customWidth} onChange={this.handleChange}>
          {this.state.data.map((row, i) => <ComboItem key={i} _id={row._id} label={row.name}/>)}
        </DropDownMenu>
      </MuiThemeProvider>
    )
  }
}

export class ComboItem extends React.Component {
  render() {
    return (
      <MenuItem style={styles.customWidth} value={this.props._id} key={this.props._id} primaryText={this.props.label}/>
    )
  }
}

在我的 index.js 文件中添加了 injectTapEventPlugin

最后它显示了输出,但是当我点击一个项目时,如果下拉到所选项目(就像普通的选择框),它永远不会改变值。

注意:onChange 方法从未调用过任何更改。

演示:

看来您还需要将 this.state.value 作为 value 属性传递给 DrowDownMenu 组件:

<DropDownMenu 
  style={styles.customWidth} 
  value={this.state.value} 
  onChange={this.handleChange}
>
  {this.state.data.map((row, i) => <ComboItem key={i} _id={row._id} label={row.name}/>)}
</DropDownMenu>

编辑:

因为您正在包装 MenuItem 组件,所以您实际上需要将 onTouchTap 函数传递给 MenuItems:

class ComboItem extends React.Component {
  render() {
    return (
      <MenuItem 
        value={this.props._id} 
        key={this.props._id} 
        primaryText={this.props.label} 
        onTouchTap={this.props.onTouchTap}
      />
    );
  }
}

这通常由 Menu 组件 here 完成。