首页 > 解决方案 > 如何在 AutoComplete Material UI 的 TextField 中设置选定值

问题描述

我有对象数组

const top100Films = [{ title: 'The Shawshank Redemption', year: 1994 },{ title: 'The Godfather', year: 
1972 },{ title: 'The Godfather: Part II', year: 1974 },{ title: 'The Dark Knight', year: 2008 },{ 
title: '12 Angry Men', year: 1957 }]

我正在使用 Material UI 的自动完成

<Autocomplete
                // value={val}
                options={top100Films}
                getOptionLabel={option => option.title}
                style={{ width: 300 }}
                onChange={(event, value) => console.log(value)}
                renderInput={params => (
                    <TextField
                        {...params}
                        label="label"
                        variant="outlined"
                        fullWidth

                    />
                )}
            />

它只是在 TextField 中显示值,但实际上并没有像这样设置值

<input
        type="text"
        value={props.value}
        onChange={e => props.onChange(e.target.value)}
      /> 

此输入设置值。

我想在 Autofield 的 TextField 中设置值,而不仅仅是显示它。如何做呢?我已经搜索过,但找不到任何解决方案。

如果有人需要任何进一步的信息,请告诉我。

标签: reactjsreact-hooksmaterial-table

解决方案


您的意思是这样的,您可以将状态设置为另一个值并实际让自动完成更改它吗?

https://codesandbox.io/s/modest-hertz-zzc19?file=/src/App.js

材质 UI 文档


推荐阅读