【问题标题】:How to conditionally pass data in react js?如何在反应js中有条件地传递数据?
【发布时间】:2020-11-06 22:54:51
【问题描述】:

我正在尝试控制我的数据onApplyClick 事件。当我传递所有数据时它工作正常,但是当我尝试有条件地传递数据时它会抛出错误。

我的主要组件代码是

            <MyComponent
                onApplyClick={(
                    myData: First & {
                        newData: Second;
                    }
                ) => console.log(myData)}
                getData={getData}       
            />

First & Second 是一个接口。现在我正在使用 onApplyClick 事件传递所有数据,例如 -

            onApplyClick={() => {
                let AData= {
                    first: "one",
                    second: "two
                };
                onApplyClick({
                    newData: AData,
                    Bdata: "three",
                    Cdata: "four"
                });
            }}

第二个界面是-

export interface Second  {
    first : string;
    second: string;
}

第一个界面是-

export interface First {
    Bdata? : string;
    Cdata? :string;
}

现在,如果条件为真,我想传递 Bdata,如果条件为假,那么我想传递 Cdata onApplyClick

我正在尝试使用此代码传递数据 -

                onApplyClick({
                    newData: AData,
                    if(condition==true) {
                      Bdata: "three",
                    }
                    else {
                      Cdata: "four"
                    }
                });

onApplyClick 事件中传递条件时出现错误。如何有条件地传递数据?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我认为在这种情况下最好的方法是使用不同的数据创建两个回调。

    或者用数据创建条件:

    const data = condition ? data1: data2;
    

    然后在回调中传递。

    onClick={() => callback(data)}
    

    最好的问候。

    【讨论】:

      【解决方案2】:

      试试这个

       <MyComponent
               onApplyClick={( condition ?  { myData: First}:{ newData: Second}) => console.log(myData)}
               getData={getData}       
                  />
      

      【讨论】:

      • 我只想在 newData 中创建条件。仅在 Bdata 和 Cdata 中。
      • 你的意思是只在 newData 中的条件,你想要的输出是什么
      • 期望的输出是 onApplyClick({ newData: AData Bdata: "three" });或 onApplyClick({ newData: AData Cdata: "four" });
      • 你的意思是 onApplyClick({ newData: AData , Bdata: "three" });或 onApplyClick({ newData: AData , Cdata: "四" });
      【解决方案3】:

      对象内不能有条件。您需要做的是将该条件置于对象之外,并在每个子句中返回不同的对象。

      onApplyClick( condition ? {newData: AData, Bdata: "three"} : {newData: AData, Cdata: "four"} )
      

      【讨论】:

      • 你能举个例子吗?
      • @AnuragMishra 我添加了一个示例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多