【问题标题】:Passing Checkbox state in a stepper component在步进器组件中传递复选框状态
【发布时间】:2020-05-01 13:44:52
【问题描述】:

我正在学习 React,我深入研究了钩子,因为它们很优雅,最大限度地减少了类的使用,并且(起初)看起来很容易理解。使用 Material-ui 的步进器和复选框组件。我正在尝试导出所选内容的值并将其显示在步进器的下一步中。已检查:这但在我的情况下似乎太复杂了。我不确定是否需要将状态数组作为道具传递并在返回 2 个复选框的组件时传递它或映射数组并通过函数传递它?

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() {...}

【问题讨论】:

  • 您可以将状态保留在同时呈现&lt;Checkboxes /&gt; 和&lt;SelectedBoxes /&gt; 的父组件中
  • 你能在codesandbox.io 中创建这个吗?我认为您需要做的是创建一个parent,然后将回调传递给不同的步骤。

标签: reactjs angular-material-stepper


【解决方案1】:

react 中有概念:Lifting up the state。在您的情况下,您可以拥有一个调用函数getStepContent 的父组件。将状态从checkbox component 提升到父组件。将handleChange 函数作为道具传递给&lt;Checkboxes handleChange={handleChange} /&gt; 等复选框。那么当step改变时,可以将checkbox状态传递给&lt;SelectedBoxes checkboxState={checkboxState} /&gt;

const [checkboxState, setCheckboxState] = useState({
    checkedA: false,
    checkedB: false,
})

const handleChange = (event) => {
    setCheckboxState({ ...state, [event.target.name]: event.target.checked });
}

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

【讨论】:

  • 我在步进器组件中有这个...:无法读取未定义的属性“handleChange”
  • 我不明白你的问题。你有这个工作演示吗?在我的回答中,我刚刚定义了您可以采取的方法。它不是完整的工作代码。
猜你喜欢
  • 1970-01-01
  • 2012-06-01
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 2014-04-16
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多