我已经开始研究react typescript了。我正在使用语义ui创建一个下拉组件。问题是语义Ui提供了更容易理解的java脚本格式的代码。我需要将以下代码转换为typescript。我成功地做了一些但是在向memberOptions添加新值时转换handleAddition有问题。 以下是JS的代码。
我不确定我是否可以在打字稿中使用setState。
const memberOptions = [
{
text: 'Bruce',
value: 'bruce'
},
{
text: 'Clark',
value: 'clark'
},
{
text: 'Diana',
value: 'diana'
},
{
text: 'Peter',
value: 'peter'
}
];
class DropdownExampleAllowAdditions extends Component {
state = { memberOptions }
handleAddition = (e, { value }) => {
this.setState({
memberOptions: [{ text: value, value },
...this.state.memberOptions],
})
}
handleChange = (e, { value }) => this.setState({ currentValues: value })
render() {
const { currentValues } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Languages'
value={currentValues}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>`enter code here`
)
}
}
我需要将handleAddition转换为typescript。是否有一些关于他们的规则?
答案 0 :(得分:0)
Here is the solution. The trick is how you manage the state.
const options = [
{
text: 'Bruce',
value: 'bruce'
},
{
text: 'Clark',
value: 'clark'
},
{
text: 'Diana',
value: 'diana'
},
{
text: 'Peter',
value: 'peter'
}
];
interface Props {
options? : any
}
export default class DropdownExampleAllowAdditions extends React.PureComponent<Props> {
constructor(props: Props) {
super(props);
this.state = {options:{}};
}`enter code here`
const handleAddition = (e: {}, {value}: {value:string}) => {
this.setState({
options: [{ text: value, value }, ...this.state.options],
})
}
const handleChange = (e: {}, { value }: { value: string }) =>
form.setFieldValue(fieldName, value);
render() {
const { options } = this.props;
return (
<Dropdown
options={this.state.options}
placeholder='Choose Languages'
value={currentValues}
onAddItem={handleAddition}
onChange={handleChange}
/>`enter code here`
)
}
}