简体   繁体   English

如何在 reactjs(钩子)中使用更改事件

[英]How use on change event in reactjs (hooks)

I need to change activeTab by onchange click on tab component.我需要通过 onchange 单击选项卡组件来更改 activeTab。 I think I need use reacts hooks.我想我需要使用反应钩子。 But I'm still can't understand how it is work.但我仍然无法理解它是如何工作的。 This code throw error此代码抛出错误

'handleChange is not defined' 'handleChange 未定义'

function TobaccoLine({ match, location  }) {
   const activeTab = useSelector(state => location.state ? location.state.activeTab : 0);

   handleChange = (event, value) => {
      this.setState({ activeTab: value });
   }

    return (
         <div className="userProfile-wrapper">
                     <Tabs
                        value={activeTab}
                        onChange={handleChange}
                        variant="scrollable"
                        scrollButtons="off"
                        indicatorColor="primary"
                     >
...

Could you please help, because I'm already stuck?你能帮忙吗,因为我已经卡住了? React JS v16+反应 JS v16+

This is not class component.这不是 class 组件。 The way you're using is public class method.您使用的方式是公共 class 方法。 Since, you are using it inside functional component, it is simply a function but the function is not being declared yet.由于您在功能组件中使用它,它只是一个 function 但尚未声明 function。 So, you just need to define it:所以,你只需要定义它:

const handleChange = (event, value) => {
  this.setState({ activeTab: value }); // Next problem: See below.
}

Earlier, you were getting handleChange is undefined coz, you were using without var , let or const declaration.早些时候,你得到了handleChange is undefined coz,你使用的是没有varletconst声明。

Next problem: You're using this.setState inside functional component which is not applicable.下一个问题:您在不适用的功能组件中使用this.setState You'll need to use useState hook:您需要使用useState钩子:

const [activeTab, setActiveTab] = useState('') // empty initial state, change it
// To set state:
setActiveTab('your value')
// To get state:
console.log(activeTab)

If you don't know about hooks, then you can learn more about it here .如果您不了解 hooks,那么您可以在此处了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM