gpt4 book ai didi

javascript - Typescript React 泛型函数类型

转载 作者:行者123 更新时间:2023-11-30 19:24:49 26 4
gpt4 key购买 nike

我有一个案例:

interface State {
Mark: boolean;
Jane: boolean;
}

React.Component<{}, State> {

state = {
Mark: false,
Jane: false,
};

fn = (name: string) => () => {
this.setState({ [name]: true });
^^^^^^^^^^
}

render () {
return
['Mark', 'Jane'].map((name) => <div onClick={this.fn(name)}>{name}</div>);

}

我收到错误:

Argument of type '{ [x: string]: boolean; }' is not assignable 
to parameter of type 'State | Pick<State, "Mark" | "Jane">

我可以为它做两个独立的功能,但我想保持它的通用性。我怎样才能使它通用以便错误消失?

最佳答案

原来这是ts编译器本身的限制。检查此问题以获取更多信息:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/26635

现在要解决您的问题,您可以使用带有回调版本的 setState。像下面这样:

interface State {
Mark: boolean;
Jane: boolean;
}

type StateKeys = keyof State

class Test extends React.Component <{}, State > {

state = {
Mark: false,
Jane: false,
};

fn = (name: StateKeys) => () => {
this.setState(prev => ({ ...prev, [name]: true }));
}

render() {
return ['Mark', 'Jane'].map((name: StateKeys) => <div onClick={this.fn(name)}>{name}</div>);

}
}

关于javascript - Typescript React 泛型函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com