如何在不重复代码的情况下拥有条件按钮。反应

Posted

技术标签:

【中文标题】如何在不重复代码的情况下拥有条件按钮。反应【英文标题】:How can I have conditional buttons without repeating code. React 【发布时间】:2021-12-14 11:57:14 【问题描述】:

我正在尝试使按钮仅在我的创建页面中可见。我已经想出了如何做到这一点,尽管以这样的方式重复代码

if (mode != "view") 

  return (
    <>
      <section
        className=`col-md-$sectionInputArray.width justify-content border-end mt-2 mb-2`
      >
        <h4 className="border-bottom">`$sectionInputArray.name` </h4>
        <div className="col-12"></div>
        sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput=input
            formData=formData
            setFormData=setFormData
            options=options
            mode=mode
            staticVars=staticVars
            SetStaticVars=SetStaticVars
            i=i
            idx=idx
            arrayLength=arrayLength
            sectionUID=sectionInputArray.UID
          />
        )) 

        /* Button to add new field */
        <button
          id ="TestButton1"
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick=() => 
            // console.log(`$sectionInputArray.name section will be added`);
            // console.log( formDataTarget: formData[sectionInputArray.UID] );

            // New Inbound Rule
            // console.log([
            //   ...formData[sectionInputArray.UID],
            //   NestedListIDSingle(sectionInputArray),
            // ]);

            let addedFormData = 
              ...formData,
              [`$sectionInputArray.UID`]: [
                ...formData[sectionInputArray.UID],
                NestedListIDSingle(sectionInputArray),
              ],
            ;

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z]+/g, "")
              .substr(0, 11);

            let withRandom = 
              ...addedFormData,
              rand_value: randomVal,
            ;

            // console.log( addedFormData: addedFormData );

            setFormData(withRandom);
          
        >
          Add New sectionInputArray.name
        </button>

        /* Button to remove section (or created form) */
        <button
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick=() => 
            console.log(
              `$sectionInputArray.name-$idx section will be removed`
            );
            // formData[sectionInputArray.UID].splice(idx, 1);

            let formDataTarget = formData[sectionInputArray.UID];
            // console.log(formDataTarget);

            let newFD = formData;

            newFD[sectionInputArray.UID].splice(idx, 1);

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z]+/g, "")
              .substr(0, 11);

            let withRandom = 
              ...newFD,
              rand_value: randomVal,
            ;

            setFormData(withRandom);
          
        >
          Remove sectionInputArray.name
        </button>

      </section>
      </>
      
      );
     else 
      return (

        <>
      <section
        className=`col-md-$sectionInputArray.width justify-content border-end mt-2 mb-2`
      >
        <h4 className="border-bottom">`$sectionInputArray.name` </h4>
        <div className="col-12"></div>
        sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput=input
            formData=formData
            setFormData=setFormData
            options=options
            mode=mode
            staticVars=staticVars
            SetStaticVars=SetStaticVars
            i=i
            idx=idx
            arrayLength=arrayLength
            sectionUID=sectionInputArray.UID
          />
        )) 
        
        </section>
        </>
        
      )

正如您在上面看到的,当它不在视图页面上时,它将不会使用按钮,因为它在“else”部分中被删除。

当按钮是有条件的时,我怎么能创建一个实例。我尝试在按钮部分之前放置一个 if 语句,但这不起作用

【问题讨论】:

【参考方案1】:

如果内容相同,您可以使用 Fragments 并有条件地显示按钮:

  return (
    <>
      <section
        className=`col-md-$sectionInputArray.width justify-content border-end mt-2 mb-2`
      >
        <h4 className="border-bottom">`$sectionInputArray.name` </h4>
        <div className="col-12"></div>
        sectionInputArray.contents.map((input, i) => (
          <NestedDynamicInputCreation
            singleInput=input
            formData=formData
            setFormData=setFormData
            options=options
            mode=mode
            staticVars=staticVars
            SetStaticVars=SetStaticVars
            i=i
            idx=idx
            arrayLength=arrayLength
            sectionUID=sectionInputArray.UID
          />
        )) 
        mode !== 'view' && (
        <>
                   <button
          id ="TestButton1"
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick=() => 
            // console.log(`$sectionInputArray.name section will be added`);
            // console.log( formDataTarget: formData[sectionInputArray.UID] );

            // New Inbound Rule
            // console.log([
            //   ...formData[sectionInputArray.UID],
            //   NestedListIDSingle(sectionInputArray),
            // ]);

            let addedFormData = 
              ...formData,
              [`$sectionInputArray.UID`]: [
                ...formData[sectionInputArray.UID],
                NestedListIDSingle(sectionInputArray),
              ],
            ;

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z]+/g, "")
              .substr(0, 11);

            let withRandom = 
              ...addedFormData,
              rand_value: randomVal,
            ;

            // console.log( addedFormData: addedFormData );

            setFormData(withRandom);
          
        >
          Add New sectionInputArray.name
        </button>

        /* Button to remove section (or created form) */
        <button
          className="btn btn-primary bt-btn m-3"
          type="button"
          onClick=() => 
            console.log(
              `$sectionInputArray.name-$idx section will be removed`
            );
            // formData[sectionInputArray.UID].splice(idx, 1);

            let formDataTarget = formData[sectionInputArray.UID];
            // console.log(formDataTarget);

            let newFD = formData;

            newFD[sectionInputArray.UID].splice(idx, 1);

            let randomVal = Math.random()
              .toString(36)
              // .replace(/[^a-z]+/g, "")
              .substr(0, 11);

            let withRandom = 
              ...newFD,
              rand_value: randomVal,
            ;

            setFormData(withRandom);
          
        >
          Remove sectionInputArray.name
        </button>
        </>
        )
      </section>
      </>
      
      );
    

【讨论】:

【参考方案2】:

是的,您可以这样做 - 将您的 conditional rendering (operator &&) 放在您的 &lt;NestedDynamicInputCreation 之后

return (
  <>
    <section
      className=`col-md-$sectionInputArray.width justify-content border-end mt-2 mb-2`
    >
      <h4 className="border-bottom">`$sectionInputArray.name` </h4>
      <div className="col-12"></div>
      sectionInputArray.contents.map((input, i) => (
        <NestedDynamicInputCreation
          singleInput=input
          formData=formData
          setFormData=setFormData
          options=options
          mode=mode
          staticVars=staticVars
          SetStaticVars=SetStaticVars
          i=i
          idx=idx
          arrayLength=arrayLength
          sectionUID=sectionInputArray.UID
        />
      )) 
      mode != 'view' && (
        <>
          <button
            id ="TestButton1"
            className="btn btn-primary bt-btn m-3"
            type="button"
            onClick=() => 
              ...
            )
          >
            Add New sectionInputArray.name
          </button>
          <button
            className="btn btn-primary bt-btn m-3"
            type="button"
            onClick=() => 
              ..
            )
          >
            Remove sectionInputArray.name
          </button>
        </>
      )
    </section>
  </>
);

【讨论】:

以上是关于如何在不重复代码的情况下拥有条件按钮。反应的主要内容,如果未能解决你的问题,请参考以下文章

如何在不阻止UI的情况下暂停指定时间的Java? [重复]

如何在不重复代码的情况下在所有控制器中显示警报?

如何在不单击后退按钮的情况下隐藏键盘[重复]

如何在不重复标题的情况下创建表格?

如何使表格视图单元格中的按钮工作[重复]

如何在不使用服务的情况下将子组件之间的反应式表单数据传递给父组件