如何在 Material UI 自动完成组件中捕获选项选择事件?

How to capture option selected event in Material UI autocomplete component?

我正在使用带有 filterOptions 的自动完成组件来建议创建一个新值,如下所示:

<Autocomplete
        multiple
        name="participant-tags"
        options={people}
        getOptionLabel={(option) => option.name}
        renderInput={(params) => {
            return (
                <TextField
                    {...params}
                    variant="outlined"
                    label="Participants"
                />
            )
        }}
        filterOptions={(options, params) => {
            const filtered = filter(options, params);
            logger.debug('filterOptions(params) %j', params)

            // Suggest the creation of a new value
            if (params.inputValue !== '') {
                filtered.push({
                    inputValue: params.inputValue,
                    name: `Add "${params.inputValue}"`,
                });
            }

            return filtered;
        }}
        onKeyDown={(e) => {
            if(e.keyCode === 13) {
                // TODO: select currently highlighted option
                e.preventDefault()
            }
        }}
        onChange={(e, value, reason) => {
            logger.debug(e.type)
            logger.debug(value)
            logger.debug(reason)
            e.preventDefault()
        }}
    />

但是,我不知道在哪里处理 "Add this option" 的选择以实际添加选项?

这已利用 onChange 处理程序中的 'reason' 参数解决,不需要 onKeyDown 处理程序:

        filterOptions={(options, params) => {
            const filtered = filter(options, params);
            if (params.inputValue !== '') {
                filtered.push({
                    inputValue: params.inputValue,
                    [displayOptionsField]: `Add New ${newOptionLabel} "${params.inputValue}"`,
                });
            }
            return filtered;
        }}
        onChange={(e, value, reason) => {
            let newOptions
            if (reason==='select-option') {
                const last = value.pop();
                if (last.inputValue) {
                    newOptions = value.concat([{[displayOptionsField]: last.inputValue}])
                }
                else {
                    newOptions = value.concat([last])
                }
            }
            if (reason==='create-option') {
                const last = value.pop();
                newOptions = value.concat([{[displayOptionsField]: last}])
            }
            if (reason==='remove-option') {
                newOptions = value
            }
            if (newOptions) {
                onChange(newOptions)
            }
        }}

onChange 处理程序中的 onChange 作为包装组件的道具。