反应打字稿,函数作为 prop 传递,但无法访问



我正在用react + typescript制作一个简单的切换按钮。我想通过将函数作为道具传递给子组件来练习一些复杂的功能。我记得这个。Props允许我访问typescript中传递给child的所有Props。如果我在parent中定义了一个函数,我应该可以在child中调用这个函数,对吧?

但是我得到了下面的错误。有人能帮帮我吗?谢谢你。

错误:

(财产)React.DOMAttributes.onClick ?:反应。MouseEventHandler |未定义Type '(checked: boolean) =>void'不能赋值给'MouseEventHandler'类型。参数"checked"one_answers"event"的类型不兼容。类型'MouseEvent'不能赋值给类型'boolean'.ts(2322)

代码:

src/

import React from 'react';
import ReactDOM from 'react-dom';
import Switch from './Switch';
interface State {
buttonOn: boolean;
}
class App extends React.PureComponent<{}, State> {
public state: State = {
buttonOn: false,
};
onChange = (checked: boolean) => this.setState({ buttonOn: checked });
render() {
return (
<div>
<Switch
checked={this.state.buttonOn}
onChange={(checked) => this.onChange(!checked)}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app')!);

src/开关/

import React from 'react';
import './index.css';
interface Props {
checked: boolean;
onChange: (checked: boolean) => void;
disabled?: boolean;
}
export default class Switch extends React.PureComponent<Props> {
render() {
return (
<div>
<div onClick={this.props.onChange} /> {/* error here */}
</div>
);
}
}

所以你有两个选择…

  1. 这样做,其中this.props.onChangeonClicklambda函数返回。如果你想
  2. ,你也可以用大括号括起来
export default class Switch extends React.PureComponent<Props> {
render() {
return (
<div>
<div onClick={(e) => this.props.onChange} /> {/* error here */}
</div>
);
}
}

或;

  1. 改变你的类型…它总是值得悬停在一个属性,如onClick了解函数签名以及传入的参数类型。
# src/App.tsx
import React from "react";
import Switch from "./Switch";
interface State {
buttonOn: boolean;
}
class App extends React.PureComponent<{}, State> {
public state: State = {
buttonOn: false
};
onChange = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
console.log(event);
};
render() {
return (
<div>
<Switch checked={this.state.buttonOn} onChange={this.onChange} />
</div>
);
}
}
export default App;

Then in the Switch:

# src/Switch.tsx
import React from "react";
interface Props {
checked: boolean;
onChange: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
disabled?: boolean;
}
export default class Switch extends React.PureComponent<Props> {
render() {
return (
<div>
<button onClick={this.props.onChange}> Hello world </button>
</div>
);
}
}

我在这里写了一个Codesandbox playground,这样你就可以自己测试了。

最新更新