【问题标题】:Pass a large object of element attribute props to component将元素属性道具的大对象传递给组件
【发布时间】:2020-04-11 22:04:23
【问题描述】:

有没有一种简单的方法可以通过对象传递元素属性的“大”对象?

例如:

const myAttrs = {
    one: "one",
    two: "two",
    ...,
    fifty: "fifty"
};

return(
    <MyElement data={myAttrs}>Some label</MyElement>
);

这样我就可以在定义的元素本身中访问和设置所有这些值...

const MyElement = styled.a.attrs(props => ({
    // I want to break down and set each object prop here, rather than
    // do it all individually like...
    //
    // one: props.one,
    // two: props.two,
    // ...
}))`
    // CSS here...
`;

【问题讨论】:

    标签: javascript html reactjs styled-components


    【解决方案1】:

    使用spread 运算符

    <MyElement {...myAttrs}>Some label</MyElement>
    
    const MyElement = styled.a.attrs({one, two, three} => ({
       // you can access these properties directly by using one for props.one and so on
    

    【讨论】:

    • 如何在定义中访问它?
    • myAttrs.one 相当于 props.one 等等
    • 在反应中,您不能直接从子变量中设置父变量,因此要设置它们,您必须将 setter 方法作为道具传递
    • 所以没有简单的方法可以省去像{one:props.one, two: props.two, ...}这样的步骤?
    • 在你的传播工作的背后,我找到了一种方法,我认为我可以包含我喜欢的所有属性。基本上我们可以按照您的建议进行操作:&lt;MyElement {...myAttrs}&gt;Label&lt;/MyElement&gt;,但是在const 中,我们可以轻松访问,而不是单独突出显示属性,我们可以简单地写export const MyElement = styled.a.attrs(props =&gt; props)`...`,这将通过ALL 对象中定义的道具,并按照您定义的方式将它们附加到 HTML 元素。
    【解决方案2】:

    将大量道具从父母传递给孩子

     <Content
          accounts={this.props.accounts}
          showBalance={this.props.showBalance}
          withdraw={this.props.withdraw}
          deposit={this.props.deposit}
          current={this.props.current}
          depositAmount={this.props.depositAmount}
          handleDeposit={this.props.handleDeposit}
          handleRm={this.props.handleRm}
          amounts={this.props.amounts}
          getWithdraw={this.props.getWithdraw}
        />;
    

    可以替换为

     <Content {...this.props} />
    

    你可以在子组件中销毁

        const {accounts,showBalance,withdraw,.....,getWithdraw} = this.props;
    

    【讨论】:

    • Crikey,这将是一个漫长的过程!不过我明白你的意思。也许像@kooskoos 所建议的那样,传播数据更合适。
    • @physicsboy 请看上面我已经编辑过的代码。我希望它可以满足您的要求。
    【解决方案3】:

    在@kooskoos 完成的传播工作的背后,我找到了一种方法,我认为我可以包含我喜欢的所有属性。

    基本上我们在 HTML 中包含展开的对象

    <MyElement {...myAttrs}>Label</MyElement>
    

    然后在const 中我们可以通过轻松访问这些道具(而不是单独突出显示属性),我们可以简单地这样写:

    export const MyElement = styled.a.attrs(props => props)`...`
    

    这将传递对象中定义的所有道具,并按照您定义的方式将它们附加到 HTML 元素。

    <MyElement one="one" two="two" three="three" ...>Label</MyElement>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2021-12-21
      • 2018-12-05
      • 2021-10-04
      • 2021-10-15
      相关资源
      最近更新 更多