【问题标题】:Updating multi-select options from state doesn't trigger material_select so options don't appear从状态更新多选选项不会触发 material_select 因此选项不会出现
【发布时间】:2019-06-27 01:54:50
【问题描述】:

我正在根据组件的状态更新选择的选项。

状态最初设置为空数组,但一旦从 API 加载,状态就会更新,因此选项应该更新。

虽然这确实发生了(并且可以在开发工具中看到),但似乎需要调用 material_select 来更新它的外观。

我可以通过从控制台调用 $("select").material_select() 来使其正确显示。

我认为导致问题的线路在这里:https://github.com/react-materialize/react-materialize/blob/master/src/Input.js#L38

有没有一种方法可以在我的组件中手动调用它?

请注意,我使用的是 create-react-app。

<Row>
  <Input
    id="categories"
    type="select"
    label="Categories"
    multiple={true}
    onChange={this.handleChange}
    s={12}
  >
    {this.state.categories.map(category => {
      return (
        <option key={category._id} value={category._id}>
          {category.name}
        </option>
      );
    })}
  </Input>
</Row>

【问题讨论】:

    标签: reactjs materialize create-react-app


    【解决方案1】:

    一旦您的选项从 API 到达,您可以通过渲染 Input 组件来解决此问题。

    您可以将状态初始化为 null 而不是空数组:

    state = {
      categories: null;
    }
    

    So in your render method, render the component conditionally (only if options are available):

    render() {
        return (
          <Row>
            {this.state.categories ? (
              <Input
                id="categories"
                type="select"
                label="Categories"
                multiple={true}
                onChange={this.handleChange}
                s={12}
              >
                {this.state.categories.map(category => {
                  return (
                    <option key={category._id} value={category._id}>
                      {category.name}
                    </option>
                  )
                })}
              </Input>
            ) : null}
          </Row>
        )
    }
    

    【讨论】:

    • 非常感谢! :) 对不起,如果这看起来很简单,但我是新手,我很长时间都无法理解这个问题。
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多