首页 > 解决方案 > 如何将 3 个输入元素中的单个输入元素传递给反应钩子中的组件

问题描述

我有一个呈现 3 个输入字段的组件,其中我需要在第一行显示一个元素,在不同的行中显示另外两个

例如 1. 第一步:电话号码

第二步:区号、城市

现有的userInfo.js 组件:

export const ExistinguserInfo = () => {
//some onchange code and props
 return(
 myfield.Input
    id="q-phonenumber"
    label="Phone number"
    value={PhNumber}
    maxLength={10}
  />
 myfield.Input
    id="q-areaCode"
    label="areaCode"
    value={areaCode}
    maxLength={10}
  />
myfield.Input
    id="q-city"
    label="City"
    value={city}
    maxLength={10}
  />
}

用户信息.js

export const userInfor = () => {
  //someCode
   const step1 = () => {
return {
  title: 'phonenumber',
  body: (
    <ExistinguserInfo/>
     //**I need only PhoneFiled**
  )  
}
}
const step2 = () => {
return {
  title: 'Areacode && City',
  body: (
    <ExistinguserInfo/>
     //**I need AreaCode and city field**
  ),
}


    OR

我是否需要创建一个单独的组件来显示 phoneNumber 不确定

标签: reactjsreact-reduxreact-hooks

解决方案


不要把它弄得那么复杂。只需使用 React 的组合功能。

像这样创建一个组件。

const ExistinguserInfo = (id, label, value, maxLength) => {
   return(
    myfield.Input
      id={id}
      label={label}
      value={value}
      maxLength={maxLength}
    />
  )
}

然后用必要的道具调用它。

export const userInfor = () => {
  const step1 = () => {
    return {
      title: "phonenumber",
      body: (
        <ExistinguserInfo
          id="q-phonenumber"
          label="Phone number"
          value={PhNumber}
          maxLength={10}
        />
        //**I need only PhoneFiled**
      )
    };
  };

  const step2 = () => {
    return {
      title: "Areacode && City",
      body: (
        <ExistinguserInfo
          id="q-areaCode"
          label="areaCode"
          value={areaCode}
          maxLength={10}
        />
        <ExistinguserInfo
          id="q-city"
          label="City"
          value={city}
          maxLength={10}
        />
        //**I need AreaCode and city field**
      )
    };
  };
};

推荐阅读