简体   繁体   English

在步进器组件中传递 React Hooks

[英]Passing React Hooks in a stepper component

I'm learning React and I deep dived into hooks as they are elegant, minimize the use of classes, and (at first) looked easy to understand.我正在学习 React,我深入研究了钩子,因为它们很优雅,最大限度地减少了类的使用,并且(起初)看起来很容易理解。 Using Material-ui's stepper and checkboxes component.使用 Material-ui 的步进器和复选框组件。 I'm trying to export the values of what was selected and display it on the next step of the stepper.我正在尝试导出所选内容的值并将其显示在步进器的下一步中。 Checked: This But it seems too complicated in my case.已检查: 但在我的情况下似乎太复杂了。 I'm not sure though if I need to pass the state array as props and pass it when returning the component of the 2 checkboxes or map the array and pass it through function?我不确定是否需要将 state 数组作为道具传递并在返回 2 个复选框或 map 数组的组件时传递它并通过 ZC1C425268E68385D1AB5074C17A94?

  const [state, setState] = React.useState({
    checkedA: false,
    checkedB: false,
  });

  const handleChange = (event) => {
    setState({ ...state, [event.target.name]: event.target.checked });
//In my try to export the state I'm passing it to a funcvtion every time a change is made
SelectedBoxes({state})
  };



  return (
    <FormGroup row>
      <FormControlLabel
        control={
          <Checkbox checked={state.checkedA} onChange={handleChange} name="checkedA" />
        }
        label="Secondary"
      />
      <FormControlLabel
        control={
          <Checkbox
            checked={state.checkedB}
            onChange={handleChange}
            name="checkedB"
            color="primary"
          />
        }
        label="Primary"
      />

    </FormGroup>
  );
}

//Here is where the function of Selectedboxes is defined
export function SelectedBoxes(checked) {
  return (
    <div>You selected: {checked}</div>
  );
}

function getSteps() {
  return ['Checkboxes', 'SelectedBoxes'];
}

function getStepContent(step) {
  switch (step) {
    case 0:
      return <Checkboxes />;
    case 1:
      return <SelectedBoxes />;
    default:
      return 'Unknown step';
  }
}

export default function HorizontalLinearStepper() {...}

How can I avoid making it so complicated?我怎样才能避免让它变得如此复杂?

Thank you谢谢

I solved my problem by moving the state inside the main component.我通过在主要组件内移动 state 解决了我的问题。 Then I was easily passing the props from the parent to the child compenent.然后我很容易将道具从父母传递给孩子。

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

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