在我的React应用程序中,我有一个输入,可以从下拉列表中获取价值。为此,我使用了Material-ui Autocomplete和TextField组件。
问题:如何通过单击按钮以编程方式设置输入值而不从下拉列表中进行选择?例如,我想从示例中设置“教父”,并且该值应在输入中直观显示。
import React from "react";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { TextField, Button } from "@material-ui/core";
export default function ComboBox() {
const handleClick = () => {
// set value in TextField from dropdown list
};
return (
<React.Fragment>
<Autocomplete
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
)}
/>
<Button onClick={handleClick}>Set value</Button>
</React.Fragment>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
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 }
];
您可以将所需的值存储在状态中,并将其传递给自动完成组件。
导入useState:
import React, { useState } from 'react';
使用useState:
const [val,setVal]=useState({})
单击按钮更改值
const handleClick = () => {
setVal(top100Films[0]);//you pass any value from the array of top100Films
// set value in TextField from dropdown list
};
并将此值传递给render中的组件
<Autocomplete
value={val}
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
)}
/>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句