在 React js 中传递多个道具的最佳方式

问题描述 投票:0回答:6

如图所示传递 React Props,我想知道在 React 中传递多个 props 的任何更简洁的方法。

enter image description here

javascript reactjs ecmascript-6 react-props
6个回答
13
投票

根据 React eslint 规则,出于可读性和维护原因,不建议使用 props spreading,请在此处阅读有关该规则的更多信息

所以你可以做的是要么保持原样,要么将类似的道具组合到一个对象中并传递它,例如:

const entity = { getEntity, entityKeyAccess, setEntityKeyAccess }; const display = { display, setDisplay }; const child = { childKeyAccess, setChildKeyAccess }; // And so on you get the idea I guess. <PanelEntity panelData={panelData} entity={entity} display={display} child={child} />;
现在任何使用此组件的人都可以轻松理解您的道具(当然不要忘记记录您的道具)并且您在不使用道具传播的情况下整理了组件。


11
投票
如果名称和键值相同,您可以使用

spread syntax

例子

<PanelEntity { ...{ panelData, setGetEntity, getEntity} } />
和这样做一样

<PanelEntity panelData={panelData} setGetEntity={setGetEntity} getEntity={getEntity} />
    

2
投票
是的,您可以将它们放在一个对象中,然后像这样使用 spread 将它们作为一个传递:

const Panel = (props) => { const nextProps = { key1: val1, key2: val2, key3: val3 }; return(<PanelEntity {...nextProps}/>); }
    

1
投票
可以这样通过

const Foo = () => const multipleProps = { prop1: 'value', prop2: 'value', Entity= 'entity value' }; return <PanelEntity {...multipleProps} />; }
    

0
投票
你可以做一个吸气剂来获得你需要的所有道具,然后你可以将它们传播到组件中

class Panels extends React.Component { get panelProps() { const {propA, propB} = this.props; return { propA, propB, functionA: () => this.customFunction(), functionB: (value) => this.customFunction2(value), } } render() { return( <PanelEntity { ...this.panelProps } /> ); } }
    

0
投票
兰德尔给出的例子 100% 是一个很棒的解决方案

但是当你的组件开始看起来像 OP 的道具时给一些建议 最好使用全局状态管理器(如 RTK)来清理所需的几个道具。您可以定义可以在任何地方使用的调度器和减速器

离我这边有点2c ^-^

© www.soinside.com 2019 - 2024. All rights reserved.