【问题标题】:onClick doesn't work on first click for MaterialUI FormControl API TextFieldonClick 在第一次单击 MaterialUI FormControl API TextField 时不起作用
【发布时间】:2020-06-16 15:20:55
【问题描述】:

在我的 React 应用程序中,我使用的是 MaterialUI 表单控件 API 文本字段。在 Select 标记中,我触发了一个 onClick 方法,但它仅在第一次单击后触发。我没有对这些标签应用任何隐藏的 CSS。以下是sn-p:

                    <FormControl style={{ width: '12em', marginTop: '1em' }} variant="outlined">
                        <InputLabel htmlFor="outlined-age-native-simple">Select Template</InputLabel>
                        <Select
                            native
                            label="Select-Template"
                            onClick={this.GetTemplates}

                        >
                            {templates.length &&
                                templates.map(x => (
                                    <option
                                        key={x.template_id}
                                        value={JSON.stringify(x.template_content)}
                                        style={{ border: 'solid' }}>
                                        {x.template_name}
                                    </option>
                                ))}
                        </Select>
                    </FormControl>

功能:

GetTemplates = e => {
    XRayApi.getTemplates(this.getTemplatesApiResponse);
};

我根本找不到原因。有什么帮助吗?

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您应该在代码中使用onChange={this.GetTemplates} 以使其正常工作。根据material-ui>select的official API docs,onClick不可用。现在,您的代码将变为

    <FormControl style={{ width: '12em', marginTop: '1em' }} variant="outlined">
      <InputLabel htmlFor="outlined-age-native-simple">Select Template</InputLabel>
      <Select
      native
      label="Select-Template"
      onChange={this.GetTemplates}>
            {templates.length &&
                templates.map(x => (
                    <option
                        key={x.template_id}
                        value={JSON.stringify(x.template_content)}
                        style={{ border: 'solid' }}>
                        {x.template_name}
                    </option>
                ))}
        </Select>
    </FormControl>
    

    【讨论】:

    • 我在同一个标​​签下使用了 onChange 和 onClick。通过将它们组合成 onChange 来解决它。
    【解决方案2】:

    在 Select 中尝试 onChange 而不是 onClick。

    <Select
      native
      label="Select-Template"
      onChange={this.GetTemplates}
    >
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多