我只想将状态更改为工作或离开。 我尝试使用useState,但它返回void类型。如何返回布尔类型? 我是打字稿plz的初学者,帮助我
import React, {useState, useCallback} from 'react';
import MainHeader from 'components/UI/Main/MainHeader';
interface MainHeaderState {
working: boolean,
}
const MainHeaderContainer:React.FC<MainHeaderState> = () =>{
const [working, setWorking] = useState(false);
const onWorking = useCallback(() => {
return setWorking(true);
}, [])
const onLeaving = useCallback(() => {
return setWorking(false)
} ,[])
return (
<MainHeader
working = {onWorking}
leaving = {onLeaving}
/>
);
}
export default MainHeaderContainer
答案 0 :(得分:1)
请勿使用return
关键字。
尝试一下:-
import React, {useState, useCallback} from 'react';
import MainHeader from 'components/UI/Main/MainHeader';
const MainHeaderContainer:React.FC = props =>{
const [working, setWorking] = useState(false);
const onWorking = useCallback(() => {
setWorking(true);
}, [])
const onLeaving = useCallback(() => {
setWorking(false)
} ,[])
return (
<MainHeader
working = {onWorking}
leaving = {onLeaving}
/>
);
}
export default MainHeaderContainer
MainHeader组件:-
import React from 'react';
import classes from './MainHeader.module.scss';
import { NavLink } from 'react-router-dom';
import Button from 'components/UI/Button'
interface MainHeaderProps {
working:() => void;
leaving:() => void;
}
const MainHeader: React.FC<MainHeaderProps> = props => {
return (
<div className = {classes.HeaderWrapper}>
<div className = {classes.Search}>
<input type = "text" placeholder = "Search...."/>
</div>
<div className = {classes.Navbar}>
<nav>
<span><NavLink exact to = '/notice'>notice</NavLink></span>
</nav>
<Button btnType = 'working' clicked = {props.working} btnValue = "working"/>
<Button btnType = 'leaving' clicked = {props.leaving} btnValue = "leaving"/>
</div>
</div>
)
}
export default MainHeader;
问题是您的MainHeader
的道具类型与您传递的道具值不匹配。您正在传递给它一个函数,并且它期望一个布尔值(检查您的MainHeader
组件)。因此,我只是将prop类型更改为功能,并且现在应该可以使用。
答案 1 :(得分:0)
import React from 'react';
import classes from './MainHeader.module.scss';
import { NavLink } from 'react-router-dom';
import Button from 'components/UI/Button'
interface MainHeaderProps {
working: boolean,
leaving: boolean
}
const MainHeader: React.FC<MainHeaderProps> = (working,leaving) => {
return (
<div className = {classes.HeaderWrapper}>
<div className = {classes.Search}>
<input type = "text" placeholder = "Search...."/>
</div>
<div className = {classes.Navbar}>
<nav>
<span><NavLink exact to = '/notice'>notice</NavLink></span>
</nav>
<Button btnType = 'working' clicked = {working} btnValue = "working"/>
<Button btnType = 'leaving' clicked = {leaving} btnValue = "leaving"/>
</div>
</div>
)
}
export default MainHeader;