首页 > 解决方案 > 是否可以将变量传递给 React 中的 antD Statistics 组件?

问题描述

我正在尝试将变量/函数中的数据呈现到 antD 统计组件中。看来它只能采用原始字符串或数字,但我需要将道具中的数据传递给它。

有没有解决的办法?请参阅下面的代码 - 我想将场景 [0].investment 传递给 "Statistic title="Investment" value={scenarios[0].investment}" 但它不允许这样做。下面的当前代码按原样工作,但当我用场景[0].investment 替换它时会中断

class RenderSummary extends Component {
    state = {
        clicked: false,
        hovered: false,
      };

      hide = () => {
        this.setState({
          clicked: false,
          hovered: false,
        });
      };

      handleHoverChange = visible => {
        this.setState({
          hovered: visible,
          clicked: false,
        });
      };

      handleClickChange = visible => {
        this.setState({
          clicked: visible,
          hovered: false,
        });
      };

    render() {
        const scenarios = this.props.scenarios;
        const data = [
          {
            title: 'Title 1', content: <Statistic title="Investment" value={0}/>,
          },
          {
            title: 'Title 2', content: <Statistic title="T Savings" value={0}/>,
          },
          {
            title: 'Title 2', content: <Statistic title="E Savings" value={0}/>,
          },
        ];
        const hoverContent = <div>This is hover content.</div>;
        const clickContent = <div>This is click content.</div>;
        const onClick = () => console.log("Works!");
        return(
            <div className="container">
              <div className="site-card-wrapper">
                <Row gutter={16}>
                 <Col span={12}>
                    <Card title="User Scenario 1" bordered={true}>
                        <List
                          grid={{ gutter: 16, column: 3 }}
                          dataSource={data}
                          renderItem={item => (
                            <List.Item>
                              {item.content}
                            </List.Item>
                          )}
                        />
                    </Card>
                  </Col>
                </Row>
              </div>
          </div>
        );
    }
}

props 中的场景如下

“场景:[0:{id:0,投资:0,tSavings:0,eSavings:0 ...},1:{id:0,投资:1,tSavings:1,eSavings:1 ...}]”

标签: javascriptreactjsantd

解决方案


我认为您构建scenarios数组的方式或传递它的方式是不正确的。

您如何传递scenarios给的示例RenderSummary

const App = () => {
  const scenarios = [
    {investment: 1}, // Add your other properties
    {investment: 2},
    {investment: 3},
  ]
  return <RenderSummary scenarios={scenarios}/>
}

如果你scenarios像上面一样通过,你可以按照你想要的方式传递它:

const data = [
  {
    title: "Title 1",
    content: <Statistic title="Investment" value={scenarios[0].investment} />,
  },
  {
    title: "Title 2",
    content: <Statistic title="T Savings" value={scenarios[1].investment} />,
  },
  {
    title: "Title 2",
    content: <Statistic title="E Savings" value={scenarios[2].investment} />,
  },
];

推荐阅读