将 graphql 变量传递给 Material UI 组件 [英] Pass graphql variable to the Material UI component
问题描述
我正在使用 React Typescript 并有一个自动完成材质 UI 组件.我正在尝试将查询建议纳入自动完成组件.
I'm using React Typescript and have a Autocomplete Material UI component. I'm trying to get query suggestions into Autocomplete component.
我的 graphql 查询如下所示:
My graphql queries looks like this:
查询定义:
import gql from 'graphql-tag';
import {useQuery} from 'react-apollo';
const TODOS = gql`
query todos($id: ID!) {
todo(id: $id) {
id
name
}
}
`;
查询初始化:
const { loading, error, data } = useQuery(TODOS, {
variables: { id }
});
我想创建一个自动完成组件,它将从文本字段组件中获取一个数值并将其传递给自动完成材料 ui 组件?
I want to create a autocomplete component which will take a numeric value from the textfield component and pass it on to the autocomplete material ui component?
我的数字组件如下所示:
My numeric component looks like this:
<TextField
id="filled-number"
label="Number"
type="number"
InputLabelProps={{
shrink: true,
}}
variant="filled"
/>
自动完成组件:
<Autocomplete
id="combo-box-demo"
options={idx.name}
getOptionLabel={(option: {name: string}) => option.name}
style={{width: 300}}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
/>
所以它应该从数字文本字段组件设置 id,然后将查询传递给自动完成组件?
So it should set id from the number textfield component and then pass the query to the autocomplete component?
推荐答案
我不知道 idx.name 从哪里来,但它似乎不是数组而 Autocomplete
的属性 options
需要一个数组类型作为值.
I don't know where idx.name comes from but it seems it is not an array while Autocomplete
's property options
requires an array type as a value.
您需要将 data.todo
传入 Autocomplete
道具 options
.
You need to pass data.todo
into the Autocomplete
prop options
.
然后你必须让你的 TextField 组件被状态控制.
Then you have to make your TextField component be controlled by state.
代码示例:
const Component = () => {
const [id, setId] = useState(%INITIAL_VALUE_IF_NEEDED%);
const { data } = useQuery(DATA, {
variables: { id },
});
const handleId = id => setId(id);
return (
<Fragment>
<TextField {...params}
label="Combo box"
variant="outlined"
onChange={handleChange}
/>
<Autocomplete
id="combo-box-demo"
options={data?.todo || []}
getOptionLabel={(option: {name: string}) => option.name}
style={{width: 300}}
renderInput={params => (
<TextField
{...params}
label="Combo box"
variant="outlined"
/>
)}
</Fragment>
);
}
然后每次在 useQuery 中更新 id 时,您将能够看到选项
And then every time the id updates in the useQuery you will be able to see the options
这篇关于将 graphql 变量传递给 Material UI 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!