我有一個組件,它當前正在將物件值作為正在傳播的道具。
const primaryProps = {/* about 10 key/values in here */}
<Component
{...primaryProps}
/>
這按預期作業。但現在我嘗試向OR其中添加一個并添加另一個傳播的物件。但這會引發語法錯誤。有辦法解決嗎?謝謝。
嘗試以下不起作用。
const primaryProps = {/* about 10 key/values in here. Can also be empty/null */}
const secondaryProps = {/* about 10 key/values in here */}
<Component
{...primaryProps || ...secondaryProps}
/>
<Component
`${primaryProps.join(",") || secondaryProps.join(",")}`
/>
uj5u.com熱心網友回復:
我認為這不可能在組件的道具內部完成。而且也不干凈。我建議將條件從組件中取出。
const props = condition ? primaryProps : secondaryProps
<Component {...props} />
uj5u.com熱心網友回復:
如果您只想secondaryProps在primaryPropsare時傳遞,null或者undefined您可以這樣做(但請注意,如果傳遞的物件已定義但為空,則這將不起作用):
<Component {...(primaryProps ?? secondaryProps)} />
uj5u.com熱心網友回復:
您的嘗試:
<Component
{...primaryProps || ...secondaryProps}
/>
行不通,因為您不需要傳播secondaryProps.
If primaryPropsis NULLsecondaryProps將與第一個展開語法一起使用
所以洗掉第二個...并使用:
<Component { ...primaryProps || secondaryProps } />;
小例子,切換primary以查看它的實際效果
class Child extends React.Component {
render() {
return Object.values(this.props);
}
}
class Example extends React.Component {
render() {
// const primary = { foo: 'primary' };
const primary = null;
const secondary = { bar: 'secondary' };
return <Child { ...primary || secondary } />;
}
}
ReactDOM.render(<Example />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
uj5u.com熱心網友回復:
如果有primaryProps,則將其分配給新的物件道具,否則使用secondaryProps。
const props = !!primaryProps ? primaryProps : secondaryProps;
<Component
{...props}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439774.html
標籤:javascript 反应
上一篇:Java泛型-引數中的平等約束
