简体   繁体   English

将对象作为道具传递 ReactJS

[英]Passing an Object as Props ReactJS

I have basically a two steps form, and it's are divided in switchable tabs.我基本上有一个两步表单,它分为可切换的选项卡。 The user needs to be able to go from one tab to another without losing the info already filled.用户需要能够从一个选项卡转到另一个选项卡,而不会丢失已填写的信息。 So I need to find a way to prevent React from nullifying my states.所以我需要找到一种方法来防止 React 取消我的状态。

First form Component:第一种形式组件:

const initialValues = {
  nome: "",
  cpf: "",
  email: "",
  telefone: "",
  nomeResp: "",
  cpfResp: "",
};

const 1Form = (props) => {
  const [values, setValues] = useState(initialValues);
  const handleChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };
....

I would receive the state at the father component and send it to the other component and save it as an object state.我会在父组件接收状态并将其发送到另一个组件并将其保存为对象状态。 I thought that maybe if I had a big state that would receive all the states from both forms, I could send this big state from one component to another...我想,也许如果我有一个大状态可以接收来自两种形式的所有状态,我可以将这个大状态从一个组件发送到另一个组件......

....    
         <SwipeableViews index={value} onChangeIndex={handleChangeIndex}>
            <TabPanel value={value} index={0}>
              <1Form bigState={bigStateValue}/>
            </TabPanel>
            <TabPanel value={value} index={1}>
              <2Form bigState={bigStateValue}/>
            </TabPanel>
          </SwipeableViews>
....

When you want to share state between sibling components, the first thing to try is to use a concept called state lifting .当您想在兄弟组件之间共享状态时,首先要尝试使用一个称为状态提升的概念。 Basically it consists in lifting the state up to the closest common ancestor of the sibling components (I could see you were thinking in something pointing to this direction).基本上它包括将状态提升到兄弟组件的最近共同祖先(我可以看到你正在考虑指向这个方向的东西)。

Now, since your state belongs to the parent component you need to pass a callback function to you form so you can update the state from inside the form components.现在,由于您的状态属于父组件,您需要将回调函数传递给表单,以便您可以从表单组件内部更新状态。

It would look something like this:它看起来像这样:

// Pseudo code
function Parent() {
  const [state, setState] = useState({})
  
  function handleChange() {
    // updates data
  }

  return (
    <Form1 data={state} onChange={handleChange} />
    <Form2 data={state} onChange={handleChange} />
  )
}

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

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