Dynamic object key with Typescript in React event handler

前端 未结 1 1848
南旧
南旧 2021-01-19 14:46

Similar but distinct from How do I dynamically assign properties to an object in TypeScript?

I have a component with the state type:

{
  low: string
         


        
相关标签:
1条回答
  • 2021-01-19 15:36

    In the perfect world we should be able to write something like this:

    private handleChange = (e: {target: {name: "low" | "high", value: string}}) =>
    {
        const { name, value } = e.target;
    
        this.setState({[name]: value});
    }
    

    But unfortunately a reported bug (see here or here) force us to use some temp workaround like casting to any or such:

    this.setState({[name]: value} as any);
    
    0 讨论(0)
提交回复
热议问题