更改界面中的状态道具 - React
我在接口中有一个布尔值。我用它来更改侧边栏的一些 CSS。
我想要一个按钮来更改 sidebarOpen
属性的状态,
这是我的尝试:
interface ISidebar {
logout?: boolean;
sidebarOpen?: boolean;
}
class Sidebar extends Component<ISidebar> {
render() {
const handleSidebar = () => {
this.props.sidebarOpen ? this.props.sidebarOpen(false) : this.props.sidebarOpen(true);
};
return (
[...]
<button onClick={handleSidebar} className="buttonSideBar">-</button>
[...]
此 handleSidebar
方法不起作用。我有一个打字稿错误:类型“Boolean”没有调用签名。
知道我如何才能完成这项工作吗?
I have a boolean in an Interface. I use it to change some CSS for a sidebar.
I want a button to change the state of the prop sidebarOpen
Here is my attempt :
interface ISidebar {
logout?: boolean;
sidebarOpen?: boolean;
}
class Sidebar extends Component<ISidebar> {
render() {
const handleSidebar = () => {
this.props.sidebarOpen ? this.props.sidebarOpen(false) : this.props.sidebarOpen(true);
};
return (
[...]
<button onClick={handleSidebar} className="buttonSideBar">-</button>
[...]
This handleSidebar
method does not work. I have a typescript error : Type 'Boolean' has no call signatures.
Any idea how I can make this work ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的界面签名(更具体地说是
sidebarOpen? boolean;
部分)表示sidebarOpen
属性是一个可选的布尔值(即它是true
、false
或未定义
)。布尔值不是函数。
然后,在您的 const handleSidebar 函数中,尝试使用布尔值将 this.props.sidebarOpen 作为函数调用。
更具体地说,您尝试将它用作布尔值和函数。
当您执行 this.props.sidebarOpen 时,您将其用作布尔值吗? ... : ... 声明。然后,在每个分支中,您尝试将相同的 prop作为函数调用。如果该 prop 是布尔值,则不能将其作为函数调用。
我的猜测是您需要一些额外的道具,即一个可以打开侧边栏的功能。
它可能看起来像这样:
...然后在代码中:
我不知道您的特定程序的具体情况,但我知道您不能使用相同的 prop 作为布尔值来检查状态 和 同时执行一个函数。
Your interface signature (more specifically the
sidebarOpen? boolean;
part) says that thesidebarOpen
prop is an optional boolean value (i.e. it is eithertrue
,false
, orundefined
).A boolean value is not a function.
Then in your
const handleSidebar
function, you try to callthis.props.sidebarOpen
as a function, with a boolean value.More specifically, you try to use it as both a boolean value and a function.
You use it as a boolean value when you do the
this.props.sidebarOpen ? ... : ...
statement. Then, within each of those branches, you try to call the same prop as a function. If that prop is a boolean value, it cannot be called as a function.My guess is that you need some additional prop that is a function that will open the sidebar.
It might look something like this:
...and then later in the code:
I do not know the specifics of your particular program, but I know that you cannot use the same prop as both a boolean value for checking state and a function at the same time.