【问题标题】:Selected ListItem value using SelectableContainerEnhance in Material-UI在 Material-UI 中使用 SelectableContainerEnhance 选择的 ListItem 值
【发布时间】:2016-02-15 17:27:22
【问题描述】:

我对@9​​87654321@ 非常陌生,并尝试在我正在使用的新Meteor 应用程序上使用Material-UI 组件。我需要一个经典的用例:当用户选择或不选择某个 ListItem 时,项目列表会更改 UI。令人惊讶的是,我发现 React 对于这样的父子组件关系并不容易。

我尝试遵循Material-UI Docs,按照文档建议使用SelectableContainerEnhance class 实现SelectableList 组件。然后我就这样走了:

const {ListItem, Avatar, Divider} = mui;

App = React.createClass({
  mixins: [ReactMeteorData],

  getMeteorData() {
    return {
      players: Players.find({}, { sort: { score: -1 } }).fetch()
    }
  },

  render() {
    return (
      <SelectableList subheader="Players list">
        {this.data.players.map((player) => {
          return (
            React.Children.toArray([
              <Divider />,

              <ListItem
                value={player._id}
                primaryText={player.name}
                secondaryText={player.score}
                leftAvatar={<Avatar>{player.name}</Avatar>} />
            ])
          );
        })}
      </SelectableList>

      <Divider />

      { true /* What to do now? */ ?
       (<span>Thanks!</span>) :
       (<span>Click a player to select</span>)}
    );
  }
});

好的,列表项已变为可选状态。 但是如何知道是否选择了任何 ListItem?以及如何获取该值并根据它调整UI?

【问题讨论】:

    标签: meteor reactjs material-ui


    【解决方案1】:

    他们谈到在文档中设置valueLink。

    <SelectableList
      subheader="Players List"
      valueLink={{
        value: this.state.selectedIndex,
        requestChange: this.handleUpdateSelectedIndex
      }}>
    

    然后定义一个handleUpdateSelectedIndex来设置状态:

    getInitialState() {
      return {selectedIndex: 1};
    },
    handleUpdateSelectedIndex(e, index) {
      this.setState({
        selectedIndex: index,
      });
    },
    

    这将在您的 App 组件上为您提供this.state.selectedIndex,您可以使用它做任何您需要做的事情。

    【讨论】:

    • 我完全按照Material UI List documentation 建议的方式实现。问题是如何知道是否在组件之外选择了任何东西(即在 App 类内部,我的代码显示注释 /* What to do now? */)。我对 React 很陌生,也许这很容易,但我不明白最好的方法。
    猜你喜欢
    • 2019-08-19
    • 2021-01-08
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多