如何将 React 表单状态从应用程序传递到多个组件(功能)
How to Pass React form state from app to multiple components (functional)
我对 React 还是很陌生,所以如果这是重复的,我很抱歉 post。我正在使用 React 创建一个分布在不同页面上的表单。这个想法是拥有您从工作申请中收到的表格类型。一个有多个步骤。
我为表单的每个步骤制作了不同的组件。第一页是 主页 。想象一个按钮将您带到创建页面。然后您会看到创建页面。有一个带有 amount 和 name 的小表格。单击下一页时,您将看到 自定义页面。您可以在那里按优先级编辑预算。
在我画得不好的图片中,显然我有应用程序,还有一个预算主页来管理它的状态 children。我认为我应该这样做,因为这是我知道的唯一方法。 我遇到的问题是:我不知道如何在整个组件中正确传递状态。二:我什至不知道我在做什么是否正确。 React 文档在基于 Class 的组件中使用表单,这有点帮助,但我无法将其配置到我的问题。
非常感谢任何帮助或建议。我还想显示预算页面中的代码。
import React, { useState, useEffect, useRef } from "react";
import BudgetResultsPage from './BudgetResultsPage';
const [count, setState] = useState(0);
const handleStateCount = () => {
if(count>3) {count = 0;}
return setState(count + 1);
}
if(count === 0) {
console.log(`homepage state ${count}`)
return (
<div className={Styles.Calculator}>
<BudgetHomePage setState={count} handleStateCount={handleStateCount}/>
</div>
)
} else if(count===1) {
console.log(`budget create state ${count}`)
return (
<div className={Styles.Calculator}>
<CalculatorHeader />
<CreateBudget setState={count} handleStateCount={handleStateCount} setAmount={amount} handleAmount={handleAmount}/>
</div>
)}
其他页面的导入显然更多,组件中传递的代码也更多。这只是我处理组件的方式的一小部分。
这可能很愚蠢,但我在状态中创建一个计数,然后当提交部分表单时,计数会增加,并且它会根据计数的大小更改页面。仅适用于一种状态,但我在向其添加更多状态时遇到问题。
再次感谢!
您遇到了哪些问题?我假设你留下的那部分代码在一个组件体内(一个函数,因为你正在使用函数式方式)。
将多个 props 传递给子组件应该没有问题,即使您必须牢记其他方法(过多的 props 通常意味着有问题...)
如果您有更多问题,请告诉我。
编辑:
假设您有那个 ResultsPage
子组件,并且在您的父组件中您执行如下操作:
<ResultsPage someProp={someValue} someOtherProp={someOtherValue} />
然后在您的子组件中,您可以像这样管理这些道具:
const ResultsPage = (props) => {
// props is an object like this: { someProp: someValue, someOtherProp: someOtherValue}
... // and in the body of the function you can manipulate it however you want
}
一般来说,最好直接在参数中解构你的 props 变量,而不是总是像这样 props.someProp
等:
const ResultsPage = ({someProp, someOtherProp}) => { ... }
关于解构的更多信息here
我已经编写了一个示例功能组件来说明您的一些问题。我在家里写的,只有记事本++,所以如果你复制粘贴可能无法编译。评论将解释您的问题
import React from 'react';
import Create_budget_page from './Create_budget_page.js';
const BudgetPage = props => {
// State 1: assigning one value to the state.
// State 2: assinging a list to the state.
// State 3: assinging a object to the state.
const [simple_state, set_simple_state] = useState(false);
const [list_state, set_list_state] = useState(["Hello","World","!"]);
const [object_state, set_object_state] = useState(
{
curmenu: "human_bios",
height: "196cm",
weight: "174lbs",
eye_colour: "blue",
hair_colour: "dirty_blonde"
}
);
// there are several possiblities, here's one with a list of objects
const [list_objects, set_list_objects] = useState(
[
{count: 69, wasClicked: false},
{count: 420, wasClicked: true},
// endless possibilities, the tricky part is properly correctly updating your states deep in the list
{integers: [1,5,2,3], keys: {isAlive: false, cur_menu: "config_menu"}}
]
);
// this function updates the state that stores an object
// arguments:
// new_values_object: the programmer passes in a object to the function with the values they want to update
// an example of calling this function in a child functional component:
// props.update_object_state({height: "165cm", weight: "143lbs", hair_colour: "black"});
function update_object_state(new_values_object){
set_object_state(prevState => {
const new_obj = prevState;
// loop through object keys and update the new_obj with the object passed in as a argument
for (var key in new_values_object){
new_obj[key] = new_values_object[key];
}
// returning the new_object will update the object_state
return new_obj;
})
}
// conditionally render based on state
switch(object_state["curmenu"]){
case "home_page":
return (
// pass in
// all props, 1 prop, state
<Create_budget_page {...props} parent_id={prop.parent_id} simple_state={simple_state} list_objects={list_objects}/>
) ;
break;
// pass in function
case "human_bios":
return (
<div className="error_page" onClick={() => {props.update_parent_state({error_occured: true})}}>This is an Error Page, click me to report diagnostics</div>
);
break;
// if none of cases are met default code executes
default:
// renders nothing
return null;
}
}
我对 React 还是很陌生,所以如果这是重复的,我很抱歉 post。我正在使用 React 创建一个分布在不同页面上的表单。这个想法是拥有您从工作申请中收到的表格类型。一个有多个步骤。
我为表单的每个步骤制作了不同的组件。第一页是 主页 。想象一个按钮将您带到创建页面。然后您会看到创建页面。有一个带有 amount 和 name 的小表格。单击下一页时,您将看到 自定义页面。您可以在那里按优先级编辑预算。
在我画得不好的图片中,显然我有应用程序,还有一个预算主页来管理它的状态 children。我认为我应该这样做,因为这是我知道的唯一方法。 我遇到的问题是:我不知道如何在整个组件中正确传递状态。二:我什至不知道我在做什么是否正确。 React 文档在基于 Class 的组件中使用表单,这有点帮助,但我无法将其配置到我的问题。
非常感谢任何帮助或建议。我还想显示预算页面中的代码。
import React, { useState, useEffect, useRef } from "react";
import BudgetResultsPage from './BudgetResultsPage';
const [count, setState] = useState(0);
const handleStateCount = () => {
if(count>3) {count = 0;}
return setState(count + 1);
}
if(count === 0) {
console.log(`homepage state ${count}`)
return (
<div className={Styles.Calculator}>
<BudgetHomePage setState={count} handleStateCount={handleStateCount}/>
</div>
)
} else if(count===1) {
console.log(`budget create state ${count}`)
return (
<div className={Styles.Calculator}>
<CalculatorHeader />
<CreateBudget setState={count} handleStateCount={handleStateCount} setAmount={amount} handleAmount={handleAmount}/>
</div>
)}
其他页面的导入显然更多,组件中传递的代码也更多。这只是我处理组件的方式的一小部分。
这可能很愚蠢,但我在状态中创建一个计数,然后当提交部分表单时,计数会增加,并且它会根据计数的大小更改页面。仅适用于一种状态,但我在向其添加更多状态时遇到问题。
再次感谢!
您遇到了哪些问题?我假设你留下的那部分代码在一个组件体内(一个函数,因为你正在使用函数式方式)。
将多个 props 传递给子组件应该没有问题,即使您必须牢记其他方法(过多的 props 通常意味着有问题...)
如果您有更多问题,请告诉我。
编辑:
假设您有那个 ResultsPage
子组件,并且在您的父组件中您执行如下操作:
<ResultsPage someProp={someValue} someOtherProp={someOtherValue} />
然后在您的子组件中,您可以像这样管理这些道具:
const ResultsPage = (props) => {
// props is an object like this: { someProp: someValue, someOtherProp: someOtherValue}
... // and in the body of the function you can manipulate it however you want
}
一般来说,最好直接在参数中解构你的 props 变量,而不是总是像这样 props.someProp
等:
const ResultsPage = ({someProp, someOtherProp}) => { ... }
关于解构的更多信息here
我已经编写了一个示例功能组件来说明您的一些问题。我在家里写的,只有记事本++,所以如果你复制粘贴可能无法编译。评论将解释您的问题
import React from 'react';
import Create_budget_page from './Create_budget_page.js';
const BudgetPage = props => {
// State 1: assigning one value to the state.
// State 2: assinging a list to the state.
// State 3: assinging a object to the state.
const [simple_state, set_simple_state] = useState(false);
const [list_state, set_list_state] = useState(["Hello","World","!"]);
const [object_state, set_object_state] = useState(
{
curmenu: "human_bios",
height: "196cm",
weight: "174lbs",
eye_colour: "blue",
hair_colour: "dirty_blonde"
}
);
// there are several possiblities, here's one with a list of objects
const [list_objects, set_list_objects] = useState(
[
{count: 69, wasClicked: false},
{count: 420, wasClicked: true},
// endless possibilities, the tricky part is properly correctly updating your states deep in the list
{integers: [1,5,2,3], keys: {isAlive: false, cur_menu: "config_menu"}}
]
);
// this function updates the state that stores an object
// arguments:
// new_values_object: the programmer passes in a object to the function with the values they want to update
// an example of calling this function in a child functional component:
// props.update_object_state({height: "165cm", weight: "143lbs", hair_colour: "black"});
function update_object_state(new_values_object){
set_object_state(prevState => {
const new_obj = prevState;
// loop through object keys and update the new_obj with the object passed in as a argument
for (var key in new_values_object){
new_obj[key] = new_values_object[key];
}
// returning the new_object will update the object_state
return new_obj;
})
}
// conditionally render based on state
switch(object_state["curmenu"]){
case "home_page":
return (
// pass in
// all props, 1 prop, state
<Create_budget_page {...props} parent_id={prop.parent_id} simple_state={simple_state} list_objects={list_objects}/>
) ;
break;
// pass in function
case "human_bios":
return (
<div className="error_page" onClick={() => {props.update_parent_state({error_occured: true})}}>This is an Error Page, click me to report diagnostics</div>
);
break;
// if none of cases are met default code executes
default:
// renders nothing
return null;
}
}