Material-UI 自动完成 event.target
Material-UI Autocomplete event.target
我使用自动完成组件并且我有这样的代码:
const countries = [
{country: 'Poland', code: 'PL'},
{country: 'Germany', code: 'DE'},
{country: 'Spain', code: 'ES'},
{country: 'France', code: 'FR'}
]
const Input = ({onCountryChange}) => (
<Autocomplete
id="combo-box"
options={countries}
getOptionLabel={option => option.country}
style={{ width: 300, marginTop: 10 }}
onChange={onCountryChange}
renderInput={params => (
<TextField {...params} label="Type a country" variant="outlined" fullWidth />
)}
/>
)
onCountryChange = (event) => {
this.setState({
countryCode: event.target.textContent
});
};
现在它设置为 countryCode
来自国家选项的国家,我想改用代码(如 PL)。我有什么想法可以做到这一点吗?
你已经差不多找到答案了。我更改了 onCountryChange
函数,看看这是不是您想要的。
这是一个工作示例:https://codesandbox.io/s/brave-mccarthy-kqx97
const countries = [
{ country: "Poland", code: "PL" },
{ country: "Germany", code: "DE" },
{ country: "Spain", code: "ES" },
{ country: "France", code: "FR" }
];
class App extends React.Component {
state = {
countryCode: ""
};
onCountryChange = (object, value) => {
this.setState({
countryCode: value.code
});
};
render() {
const { countryCode } = this.state;
return (
<div className="App">
{countryCode}
<Autocomplete
id="combo-box"
options={countries}
getOptionLabel={option => option.country}
style={{ width: 300, marginTop: 10 }}
onChange={this.onCountryChange}
renderInput={params => (
<TextField
{...params}
label="Type a country"
variant="outlined"
fullWidth
/>
)}
/>
</div>
);
}
}
我使用自动完成组件并且我有这样的代码:
const countries = [
{country: 'Poland', code: 'PL'},
{country: 'Germany', code: 'DE'},
{country: 'Spain', code: 'ES'},
{country: 'France', code: 'FR'}
]
const Input = ({onCountryChange}) => (
<Autocomplete
id="combo-box"
options={countries}
getOptionLabel={option => option.country}
style={{ width: 300, marginTop: 10 }}
onChange={onCountryChange}
renderInput={params => (
<TextField {...params} label="Type a country" variant="outlined" fullWidth />
)}
/>
)
onCountryChange = (event) => {
this.setState({
countryCode: event.target.textContent
});
};
现在它设置为 countryCode
来自国家选项的国家,我想改用代码(如 PL)。我有什么想法可以做到这一点吗?
你已经差不多找到答案了。我更改了 onCountryChange
函数,看看这是不是您想要的。
这是一个工作示例:https://codesandbox.io/s/brave-mccarthy-kqx97
const countries = [
{ country: "Poland", code: "PL" },
{ country: "Germany", code: "DE" },
{ country: "Spain", code: "ES" },
{ country: "France", code: "FR" }
];
class App extends React.Component {
state = {
countryCode: ""
};
onCountryChange = (object, value) => {
this.setState({
countryCode: value.code
});
};
render() {
const { countryCode } = this.state;
return (
<div className="App">
{countryCode}
<Autocomplete
id="combo-box"
options={countries}
getOptionLabel={option => option.country}
style={{ width: 300, marginTop: 10 }}
onChange={this.onCountryChange}
renderInput={params => (
<TextField
{...params}
label="Type a country"
variant="outlined"
fullWidth
/>
)}
/>
</div>
);
}
}