React实体化芯片-Javascript插件-自动完成:如何更新状态变量



我想更新一个状态变量数组,但我不知道如何在更改时更新。我想改变数组";国家";,但当我试图将它与React实体化芯片联系起来时,它不起作用。在我选择一个选项后:

  • 要么我没有办法更新状态变量,我看到带有X的芯片将其删除
  • 要么我有更新状态的功能,但我没有看到带有X的芯片来删除它

如何使所选芯片正常显示,同时更新状态变量?谢谢

以下是我的代码也可在CodeSandbox 中获得

import React from "react";
import ReactDOM from "react-dom";
import { Icon, Chip} from 'react-materialize';
import 'materialize-css';

class App extends React.Component {
constructor() {
super();
this.state = {
name: "Venom",
countries: [{ name: 'France' }, { name: 'Germany' }],
};
}
handleAddCountry = (e) => {
console.log("Chip :")
console.log(e.target.name)
this.setState({ countries: this.state.countries.concat([{ name: e.target.value }]) });
}
handleAddFrance = (e) => {
console.log("Button:")
console.log(e.target.value)
this.setState({ countries: this.state.countries.concat([{ name: e.target.value }]) });
}
render() {
const { countries} = this.state
return (
<div>
<div>
<h1>{this.state.name}</h1>
</div>

<div>
<Chip
onChange={ this.handleAddCountry } 
close={false}
closeIcon={<Icon className="close">close</Icon>}
options={{
placeholder: 'saisir un territoire',
secondaryPlaceholder: '+territoire',
autocompleteOptions: {
data: {
'   France m&#233;tropolitaine  '   :   null,
'   DOM - TOM   '   :   null,
'   DOM '   :   null,
'   Afghanistan '   :   null,
},
limit: Infinity,
minLength: 1,
onAutocomplete: function noRefCheck(){}
}
}}
/>
</div>
<button type="button" onClick={this.handleAddFrance} value="France" className="small">Add France</button>
<br></br>    
{countries.map(country => <div>{country.name}</div>)}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);

最后,这是我找到的解决方法:

<Chip close={false}
closeIcon={<Icon className="close">close</Icon>}
options={{
onChipAdd: this.addProdTerritory,
placeholder: "saisir territoire",
secondaryPlaceholder: "+territoire",
autocompleteOptions: {
data: {
" France métropolitaine " : null  ,
" Algérie " : null  ,
" Allemagne " : null  ,
" Andorre " : null  ,
},
limit: Infinity,
minLength: 1,
onAutocomplete: function noRefCheck() {}},}}
/>

带有

this.state = {
countriesProd: [{ name: "France" }]
}
this.addProdTerritory = this.addProdTerritory.bind(this);

addProdTerritory = foo => {
var ret = foo.text().replace('close','');
this.setState({
countriesProd: this.state.countriesProd.concat([{ name: ret }])
});
};
deleteProdTerritory(i) {
const { countriesProd } = this.state;
countriesProd.splice(i, 1);
this.setState({ countriesProd });
}

在自动完成字段下面,我在第1列显示一个带有芯片的表,在第2列显示删除按钮

我在GitHub 上发现了

最新更新