【问题标题】:pass formik.values to another js file将 formik.values 传递给另一个 js 文件
【发布时间】:2020-12-25 08:14:49
【问题描述】:

我学习反应,我正在尝试创建一个步进器来正确管理我的表单,我正在寻找最合适的方式来将输入值从一个步骤传递到另一个步骤 完整代码如下

这里是第 1 步的输入值:

   <MDBInput
   label="exerciseManager"
   name="exerciseManager"
   type="text"
   value={formik.values.exerciseManager}
   onChange={formik.handleChange}
   outline
   size="lg"
   />

我想将 formik.values.exerciseManager 传递到第 2 步,以便我可以在那里使用它

第1步和第2步在不同的js文件中

我应该如何正确地做到这一点?

这是第 1 步:

我希望它显示在这里:

完整的第 1 步代码

//now check that the value get correct to the database
const Certifications = (props) => {
//state             //Setstate
const [fieldApproveOptions, setFieldApproveOptions] = useState([])

//useEffect Hooks 
useEffect(() => {

    axios.get('/api/certifications/fieldApproveOptions?userId=1234567&rank=Colonel&force=Moran')
        .then(response => {
            console.log(response.data)
            setFieldApproveOptions(response.data.fieldApproveOptions)
        }
        ).catch(err => console.log(err))
}, [])

const formik = useFormik({

    initialValues: {
        exerciseName: '',
        //exerciseBy: '',  autofill current user from session
        exerciseOOB: '',
        exercisePOD: '',
        exerciseType: '', // options should be pull from db
        exerciseLive: '',
        fieldApprove: '', // options should be pull from db
        fileApprove: '', // options should be pull from db
        artilleryApprove: '', // options should be pull from db
        exerciseManager: '',
        trainerOfficerApprove: '', // options should be pull from db
        cerRes: '',
        fieldApproveOptions: []

    },

    onSubmit: values => {
        axios.post('/api/certifications', values)
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    },
})

return (
    <Card>
        <CardContent>
            <div className="Pedding">
                <MDBContainer fluid  >

                    <MDBRow center  >
                        <MDBCol md="4"  >
                            <div className="MDBColor">
                                <form onSubmit={formik.handleSubmit} autoComplete="off">
                                    <p className="h1 text-center" style={{ paddingTop: "10px", fontWeight: "bold" }}>Certifications</p>
                                    <div className="Certifications">

                                        <MDBInput
                                            label="Exercise name"
                                            name="exerciseName"
                                            type="text"
                                            onChange={formik.handleChange}
                                            value={formik.values.exerciseName}
                                            outline
                                            size="lg"
                                        />


                                        <MDBInput
                                            label="Exercise type"
                                            name="exerciseType"
                                            list="types"
                                            onChange={formik.handleChange}
                                            value={formik.values.exerciseType}
                                            outline
                                            size="lg"

                                        />

                                        <datalist id="types" >
                                            <option data-value="1" value="Open Terrain">Open Terrain</option>
                                            <option value="Urban warfare" >Urban warfare</option>
                                            <option value="Armoured fighting vehicle" >Armoured fighting vehicle</option>
                                            <option value="unplanned" >unplanned</option>
                                            <option value="live military exercise" >live military exercise</option>
                                        </datalist>






                                        <MDBInput
                                            label="Order of battle"
                                            name="exerciseOOB"
                                            type="number"
                                            min="20"
                                            onChange={formik.handleChange}
                                            value={formik.values.exerciseOOB}
                                            outline
                                            size="lg"
                                        />



                                        {/*FieldApprove button */}
                                        <MDBInput
                                            label="fieldApprove"
                                            name="fieldApprove"
                                            list="fieldApproves"
                                            onChange={formik.handleChange}
                                            value={formik.values.fieldApprove}
                                            outline
                                            size="lg"
                                        />
                                        <datalist id="fieldApproves" defaultValue>

                                            {fieldApproveOptions.map((option, i) =>
                                                <option key={i++} value={option.id}>
                                                    {option.rank + " " + option.firstName + " " + option.lastName}
                                                </option>)}
                                        </datalist>




                                        <MDBInput
                                            label="fileApprove"
                                            name="fileApprove"
                                            type="text"
                                            value={formik.values.fileApprove}
                                            onChange={formik.handleChange}
                                            outline
                                            size="lg"
                                        />
                                        <MDBInput
                                            label="artilleryApprove"
                                            name="artilleryApprove"
                                            type="text"
                                            value={formik.values.artilleryApprove}
                                            onChange={formik.handleChange}
                                            outline
                                            size="lg"
                                        />
                                        <MDBInput
                                            label="exerciseManager"
                                            name="exerciseManager"
                                            type="text"
                                            value={formik.values.exerciseManager}
                                            onChange={formik.handleChange}
                                            outline
                                            size="lg"
                                          

                                            
                                           

                                        />
                                        

                                        <MDBInput
                                            label="trainerOfficerApprove"
                                            name="trainerOfficerApprove"
                                            type="text"
                                            value={formik.values.trainerOfficerApprove}
                                            onChange={formik.handleChange}
                                            outline
                                            size="lg"

                                        />

                                        <div style={{ fontSize: "large", fontWeight: "bold" }} className="custom-control custom-checkbox">

                                            <input type="checkbox"
                                                onChange={formik.handleChange}
                                                value={formik.values.exerciseLive}
                                                className="custom-control-input"
                                                name="exerciseLive"
                                                id="live"
                                                value="on"

                                            />
                                            <label className="custom-control-label" htmlFor="live"> live exercise</label>
                                        </div>





                                        {/*pod section*/}
                                        <span style={{ fontSize: "large", fontWeight: "bold", float: "left" }} >part of the day:</span>
                                        <div className="forms" style={{ fontWeight: "bold" }} onChange={formik.handleChange} value={formik.values.exercisePOD}  >
                                            {/*night button*/}
                                            <label htmlFor="rdo1">
                                                <input type="radio" id="rdo1" name="exercisePOD" value="night" />
                                                <span className="rdo"></span>
                                                <span>night</span>
                                            </label>
                                            {/*day button*/}
                                            <label htmlFor="rdo2">
                                                <input type="radio" id="rdo2" name="exercisePOD" value="day" />
                                                <span className="rdo"></span>
                                                <span>day</span>
                                            </label>

                                        </div>






                                        <div className="text-center">
                                            <MDBBtn type="submit" color="yellow">Send</MDBBtn>
                                        </div>
                                    </div >
                                </form >
                            </div>
                        </MDBCol>
                    </MDBRow>

                </MDBContainer >

            </div>
        </CardContent>
    </Card>
);



}

export default Certifications;

这里是 Soform.js 完整代码

        const SoForm = () => {



 return (

   <p >
{formik.values.exerciseManager}
  </p>
 )
     }
   export default SoForm;

这里形成ikStepper代码

export default function Home() {
return (
<Card>
  <CardContent>
    <FormikStepper
      initialValues={{
   
      }}
      onSubmit={async (values) => {
        await sleep(3000);
        console.log('values', values);
      }}
    >
      <FormikStep label="Certifications">
        <Box paddingBottom={2}>
        <Certifications   ></Certifications>
        </Box>
      </FormikStep>
      <FormikStep 
        label="loginPageF"

      >
        <Box paddingBottom={2}>
        <SoForm ></SoForm>
         

【问题讨论】:

  • 您想将其传递给子组件、父组件或兄弟组件……还是完全不相关的组件?如果孩子 -> 使用道具,如果父母 -> 使用回调,如果兄弟 -> 混合两者.. 完全不相关? -> 使用 react-redux
  • 您可以使用useFormik hook 来获取值。由于我不知道您的表格的详细信息,因此我不确定这是否可行。我相信在这种情况下经常使用会话存储,因为使用 redux 刷新会删除所有数据
  • @MaifeeUlAsad 您好,步骤 1 和步骤 2 在不同的 js 文件中
  • @tachko 嗨,我添加了两张图片,这样在我填写我想在第 2 步显示的文件中的图片中会更容易理解
  • 它们在不同的js文件中,它们应该是..但是它们之间的关系是什么?从您提供的插图中,我可以大胆猜测,有一些Parent 组件,其中CertificationLogin 位于...如果您提供最少的代码,我可以在那里实现它..

标签: reactjs formik stepper


【解决方案1】:

很难阅读和理解您的代码。尽量提供最少的可重复陈述。我可以理解您的问题,但无法使用您的代码。所以我创建了我的成功示例。在这里,codesandbox.io:https://codesandbox.io/s/elegant-shtern-362ki?file=/src/App.js

让我为你解释一下。

index.js -> is entry point, that calls only one component App, as we have no route
App.js -> is the parent component, which has two child, Certification and Panel
Certification.js -> takes input
Panel -> renders data from certification

如果我没记错的话,那就是你想要的。将一个组件中的数据渲染到另一个组件,它们是彼此的兄弟。

App.js:

import React from "react";
import Certifications from "./Certifications";
import Panel from "./Panel";

class App extends React.Component {
  state = {
    value1: "",
    value2: ""
  };

  fromCert = (name, value) => {
    this.setState({ [name]: value });
  };

  render() {
    return (
      <div>
        {this.state.value1}
        {this.state.value2}
        <Certifications fromCert={this.fromCert} />
        <Panel value1={this.state.value1} value2={this.state.value2} />
      </div>
    );
  }
}
export default App;

Panel.js

import React from "react";

class Panel extends React.Component {
  render() {
    return (
      <div>
        Here we will render data from App, below
        <div>{this.props.value1}</div>
        <div>{this.props.value2}</div>
        Panel ends
      </div>
    );
  }
}

export default Panel;

Certification.js

import React from "react";

class Certifications extends React.Component {
  state = {
    input1: "",
    input2: ""
  };
  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
    this.props.fromCert(e.target.name, e.target.value);
  };
  render() {
    return (
      <div>
        <input name="value1" onChange={this.onChange} />
        <input name="value2" onChange={this.onChange} />
        <div>
          Inside certificate
          <div>{this.state.input1}</div>
          <div>{this.state.input2}</div>
          Certificate ends
        </div>
      </div>
    );
  }
}
export default Certifications;

首先,认证有两种状态 - value1, value2。所以我给了两个输入的名字value1, value2。这样我就可以动态设置值。 Why? - just imagine I have 10 or 20 states. And that you have in your code.

而 onChange of value,我正在使用 fromCert 触发对 App 的回调。尝试传递 1000+ 参数,它会。 :wink:

当我从认证触发该回调时,它会在 App.js 的 fromCert 中调用。这是为什么?因为我已将该函数或方法作为参数传递 - &lt;Certifications fromCert={this.fromCert} /&gt;。这就是为什么这个函数或方法充当回调的原因。当我得到这些值时,我只是将它们设置为App.js 的状态。然后将它们作为props 传递给Panel。

因此,任何更改都会应用于 AppCertification,然后传递到 Panel

Certification -> App : Child to Parent communication
App -> Panel : Parent to Child communication
Certification -> Panel : Child to Child communication / Sibling communication

试着想象层次结构。

非常感谢。如果您有任何问题,请随时提出。

【讨论】:

  • 嗨首先我想坦克你!在那个解决方案上。但这并不能解决我的情况,是的,您理解正确的层次结构,但解决方案是针对常规 rcf,我使用 rff 而不是常规 rff 我使用 formik 钩子
  • @checkeverytime facebook推荐使用rff,但我不知道为什么我喜欢rcf...但是逻辑和底层架构是一样的,对吧??如果这可以帮助您投票..因为formik钩子只是返回该组件/功能组件的状态..所以我认为这里已经介绍了用例..谢谢..
  • 我在这里做一个简单的例子来更好地解释我的问题stackoverflow.com/questions/63925561/…
猜你喜欢
  • 2014-04-05
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
相关资源
最近更新 更多