我想更新一个状态变量数组,但我不知道如何更新更改。我想更改数组“国家”,但是当我尝试将它与 React-materialize 芯片链接时,它不起作用。在我选择了一个选项之后: - 要么我无法更新状态变量,我看到带有 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é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
);