我想更新状态变量数组,但是我不知道如何在更改时进行更新。没有事件链接到芯片。我想更改数组“国家”,但是当我尝试将其与React-materialize芯片链接时,它不起作用。
我如何从筹码中获取事件?你能帮我吗 ?谢谢
下面是我的代码也可以在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
);
最后这是我找到的解决方法:
<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() {}},}}
/>
with
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上找到了答案