[英]How to conditionally pass data in react js?
I am trying to console my data onApplyClick
event.我正在尝试控制我的数据
onApplyClick
事件。 It is working fine when I am passing all the data but when I an trying to pass data conditionally then it is throwing error.当我传递所有数据时它工作正常,但是当我尝试有条件地传递数据时,它会抛出错误。
My main component code is我的主要组件代码是
<MyComponent
onApplyClick={(
myData: First & {
newData: Second;
}
) => console.log(myData)}
getData={getData}
/>
Where First & Second is an interface.其中 First & Second 是一个接口。 Now I am passing all data using
onApplyClick
event like -现在我使用
onApplyClick
事件传递所有数据,例如 -
onApplyClick={() => {
let AData= {
first: "one",
second: "two
};
onApplyClick({
newData: AData,
Bdata: "three",
Cdata: "four"
});
}}
Second interface is -第二个界面是——
export interface Second {
first : string;
second: string;
}
First interface is -第一个界面是——
export interface First {
Bdata? : string;
Cdata? :string;
}
now I want to pass Bdata if a condition is true & if condition is false then I want to pass Cdata onApplyClick
.现在我想在条件为真时传递 Bdata 并且如果条件为假那么我想传递 Cdata
onApplyClick
。
I am trying pass data using this code -我正在尝试使用此代码传递数据 -
onApplyClick({
newData: AData,
if(condition==true) {
Bdata: "three",
}
else {
Cdata: "four"
}
});
I am getting error while passing the condition inside an onApplyClick
event.在
onApplyClick
事件中传递条件时出现错误。 How can I pass data conditionally ?如何有条件地传递数据?
I think that the best approach in this case would be to create two callbacks with defferetnt data.我认为在这种情况下最好的方法是使用 deferetnt 数据创建两个回调。
Or create condition with data:或者用数据创建条件:
const data = condition ? data1: data2;
And then pass it in callback.然后在回调中传递它。
onClick={() => callback(data)}
Best regards.此致。
try this尝试这个
<MyComponent
onApplyClick={( condition ? { myData: First}:{ newData: Second}) => console.log(myData)}
getData={getData}
/>
You can't have conditionals inside an object.对象中不能有条件。 What you need to do is take that condition outside of the object and return different objects in each clause.
您需要做的是将该条件置于对象之外,并在每个子句中返回不同的对象。
onApplyClick( condition ? {newData: AData, Bdata: "three"} : {newData: AData, Cdata: "four"} )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.