将元素属性道具的大对象传递给组件

时间:2019-12-19 10:13:51

标签: javascript html reactjs styled-components

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

例如:

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...
`;

3 个答案:

答案 0 :(得分:2)

使用<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 运算符

//var dbdata = con.MyQuery("SELECT amount, amount1 FROM cash_trans");
string query="SELECT amount, amount1 FROM cash_trans";

var myChart = new myChart(width: 600, height: 400)
  .AddTitle("CASH BooK")
  .AddSeries(chartType: "Pie",
     xValue: query, xField: "amount",
     yValues: query, yFields: "amount1")
  .Write();

答案 1 :(得分:0)

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

 <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;

答案 2 :(得分:0)

在@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>