在React Components中动态设置道具

时间:2018-07-11 23:11:50

标签: javascript reactjs

只有在接收到的对象数组中给出道具时,我才尝试在道具中设置道具,像这样:

此组件有效:

const like_content = 
    <div>
      Total likes: <b>52</b>
    </div>
<Card cols={2} dark centeredBody centeredHeader title="Likes" subtitle="Total likes in your posts" content={like_content} />

但是我要设置

  

黑暗/居中的身体/居中的标题

当这些属性位于这样的数组中时,它们在 map 函数中的

属性:

statistics: [
        {
          title: 'Likes',
          subtitle: 'Amount of likes on facebook',
          content: 58,
          props: ['dark', 'centeredHeader'] // <-- HERE
        },
        {
          title: 'Share',
          subtitle: 'Amount of Share on facebook',
          content: 58,
          props: ['dark'] // <-- HERE
        },
        {
          title: 'People reached',
          subtitle: 'Amount of people who saw you on facebook',
          content: 58,
          props: ['centeredHeader'] // <-- HERE
        }
      ]

我尝试了这个,但是当然没用:

{this.state.statistics.map((card, index) => {
              return (
                <Card 
                  key={index}
                  cols={3} 
                  title={card.title} 
                  subtitle={card.subtitle} 
                  content={card.content}
                  {card.props.map(prop => {
                    return prop;
                  })}
                />
              );
            })}
  

组件成功创建,但我无法设置我所指导的道具

2 个答案:

答案 0 :(得分:2)

您可以从数组中创建一个对象,其中数组中的每个元素都将成为对象中具有值true的键,然后将该对象散布在组件上:

{this.state.statistics.map((card, index) => {
  const propsObj = card.props.reduce((result, prop) => {
    result[prop] = true;
    return result;
  }, {});

  return (
    <Card
      key={index}
      cols={3}
      title={card.title}
      subtitle={card.subtitle}
      content={card.content}
      {...propsObj}
    />
  );
})}

答案 1 :(得分:0)

属性是键值对,因此您需要一个键和一个值。

您可以将所有道具传递给卡片,让卡片处理道具吗?

https://codesandbox.io/s/84xv754y8j

 import React, { Component } from "react";

class Card extends Component {
  render() {
    return (
      <div>
        I am a card that has{" "}
        {this.props.props.map(property => "(" + property + ") ")}
      </div>
    );
  }
}
export default Card;

//Other Class
return (        
      {statistics.map((card,index)=>{
        return <Card 
          key={index}
          cols={3}
          title={card.title}
          subtitle={card.subtitle}
          content={card.content}
          props={card.props}/>
      })}
相关问题