【发布时间】:2020-04-23 11:01:53
【问题描述】:
我必须将我的类组件转换为函数组件,因为我将不得不为 redux 使用钩子(useDispatch();) 一切似乎都很好,除了切换按钮不想工作的事情。 作为比较,我发布了一个类组件代码(一点)和功能组件代码(更多)
state = {
open: true,
role: ""
}
componentDidMount() {
if (this.props.auth.user)
{
this.setState({role: this.props.auth.user.role});
}
}
checkRole = (role) => {
if (role === 'Menager' || role === 'Technolog')
{
return true }
else
{
return false
};
}
toggleImage = () => {
if(this.checkRole(this.state.role)) {
this.setState({open: !this.state.open})
};
}
这里是功能组件代码:
const Islbutton = props => {
const [open, setOpen] = useState(true);
const [role, setRole] = useState('');
useEffect(() => {
if (props.auth.user)
{
setRole({role: props.auth.user.role});
}
});
const checkRole = (role) => {
if (role === 'Menager' || role === 'Technolog')
{
return true }
else
{
return false
};
}
const toggleImage = () => {
if(checkRole(role)) {
setOpen({open: !open})
};
}
const getImageName = () => open ? 'islOnn' : 'islOfff'
return(
<div>
<img style={islplace} src={open ? islon : isloff } onClick={()=> toggleImage(role)} />
</div>
);
}
【问题讨论】:
标签: javascript reactjs function components