我在 React 中有一个表单,根据配置,这个表单可以有多个输入。输入的顺序也将由配置控制。
这是我当前的代码:
int n;
cin>>n;
int sum=0;
int originaln=n;
while(n!=0){
int lastdigit= n%10;
sum+= pow(lastdigit,3);
n=n/10;
}
if(sum==originaln){
cout<<"Armstrong Number"<<endl;
}
else{
cout<<"Not Armstrong"<<endl;
}
return 0;
配置是 const 并且保存在
const login_fields = ["id","phone"];
function IdInput() {
if (login_fields.includes("id")) {
return (
<input ref={idInput_ref} type="text" className="form-control" />
)
}
}
function PhoneInput() {
if (login_fields.includes("phone")) {
return (
<input ref={phoneInput_ref} type="text" className="form-control" />
)
}
}
function ShowInputfields(){
return (
<>
{(() => {
login_fields.forEach((item, i)=>{
if(item==="phone") {return PhoneInput();};
if(item==="id") {return IdInput();};
});
})()}
</>
);
}
return (
<div>
<form>
{ShowInputfields()}
<div>
<button id="login-submit">Submit</button>
</form>
</div>
);
中。
上述情况的预期结果是电话字段之前的 id 字段。 (实际代码中有更多字段,例如姓名、电子邮件等)。
不幸的是代码不起作用。我收到错误:
login_fields
浏览器上没有呈现任何字段。
我应该改变什么才能达到预期的结果?
答案 0 :(得分:2)
您应该将 forEach
更改为 map
,并且您也不需要将其全部包装在匿名函数中并调用它。
所以将 ShowInputfields
改为
function ShowInputfields(){
return (
<>
{
login_fields.map((item, i)=>{
if(item==="phone") {return PhoneInput();};
if(item==="id") {return IdInput();};
});
}
</>
);
}
您也不要在 <div>
之前关闭 button
答案 1 :(得分:1)
您想要的东西是可以实现的,但是您当前的编码模式需要进行重大改进。
考虑创建一个通用组件,例如 InputField
,它接受要呈现为 type
属性的字段。
该组件的职责包括检查 type
属性,然后返回正确的字段。
按照相同的操作后,就不需要检查每个字段组件中的 login_field.include
,例如 PhoneInput
。
import React from "react";
// Assuming that Id and Phone Input are sufficiently distinct
// to justify creating separate components.
function IdInput() {
return <input type="text" className="form-control" />;
}
function PhoneInput() {
return <input type="text" className="form-control" />;
}
function InputField({ type }) {
// Checking the type
switch (type) {
case "phone":
return PhoneInput;
case "id":
return IdInput;
default:
return <input type="text" />;
}
}
function CustomForm({ formFields }) {
return (
<form>
{formFields.map((field) => (
<InputField type={field} />
))}
<button valu="submit" />
</form>
);
}