【问题标题】:How to use an array in React and convert to component如何在 React 中使用数组并转换为组件
【发布时间】:2021-06-23 15:42:59
【问题描述】:

我创建了一个网页,该网页汇集了我生成的 SQL 数据库,其中包含人的姓名、地址和工作等信息。我想出了如何通过创建一个数组并将数据放入其中然后返回来在网页上显示它。我想要做的是创建一个看起来像磁贴/名称标签的反应组件,并且是一个包含每个人/工作的框,并为每个条目创建它。我对如何创建 react 组件并使用 CSS 设置样式感到困惑。

这是我的网页代码:

    import React, { Component } from "react";

export class Dashboard extends Component {
    displanyName = Dashboard.name;

    constructor(props) {
        super(props);

        this.state = {
            people: []
        };
    }

    componentDidMount() {
        fetch("api/people")
            .then(response => response.json())
            .then(data => this.setState({ people: data }));
    }
    render() {
        //const { people } = this.state; // equivalent to next line
        const people = this.state.people;
        if (people.length > 0)

        //creates an array to iterate
        let arr = people.map((person, index) => <div key={index}>Person: {person.name} , Job: {person.job}</div>);

        return (
            <div>
                {arr}
            </div>
        );
    }
}

这样在页面上显示数组的内容: 人:鲍勃·博伯特,工作:程序员 人:Jane Doe,工作:老师 人:约翰·史密斯,工作:厨师

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    如果我理解正确,你可以试试这个。

    import ReactDOM from 'react-dom';
    import React, { Component } from 'react';
    
    export class PersonNameJob extends Component {
      render() {
        return (
          <div style={{ fontWeight: 'bold' }}>Person: {this.props.person.name}, Job: {this.props.person.job}</div>
        );
      }
    }
    
    export class Dashboard extends Component {
      // more code here...
      render() {
        const people = [
          {
            name: 'John',
            job: 'Developer',
          },
          {
            name: 'Marry',
            job: 'accountant',
          },
        ];
    
        return (
          <div>
            {people.map((person, index) => (<PersonNameJob key={index} person={person} />))}
          </div>
        );
      }
    }
    
    ReactDOM.render(
      <React.StrictMode>
        <Dashboard />
      </React.StrictMode>,
      document.getElementById('root')
    );
    

    您可以直接使用组件的样式属性或使用styled-components包来设置样式。

    export class Dashboard extends Component {
      render() {
        // logic to get people
        return (
          <div>
            {people.map((person, index) => (<StyledPersonNameJob key={index} person={person} />))}
          </div>
        );
      }
    }
    const StyledPersonNameJob = styled(PersonNameJob).`
        background-color: red;
        border: 1px solid #000;
    `;
    

    【讨论】:

    • 此方法是否涉及将此代码放在与仪表板相同的文件中或作为单独的文件(如 PersonNameJob.js 和 PersonNameJob.css)?
    • 如果PersonName组件比较小,可以和Dashboard放在同一个文件中。否则,您应该为每个文件定义一个组件。 CSS 应该在组件中定义。
    • 还有一点,你应该考虑使用功能组件而不是类组件。因为 React Hooks 可能有更好的性能,但它们只是为功能组件设计的。 reactjs.org/docs/hooks-intro.html
    • 我厌倦了把这部分放在我已经写的上面``` import React, { Component } from 'react'; export class PersonNameJob extends Component { render() { return (
      Person: {this.props.person.name} , Job: {this.props. person.job}
      ); } } ``` 但现在我收到此错误“第 7:23 行:'index' is not defined no-undef”
    【解决方案2】:

    您是否考虑过使用Material UI?我喜欢用 Material UI 来做这样的事情。 Card Component 可用于轻松制作您想要的东西。要使用材质 UI,您需要使用 npm install @material-ui/coreyarn add @material-ui/core 安装它。然后,您可以使用组件中的组件。它看起来像这样:

    import React, { Component } from "react";
    // import material UI card components
    import Card from '@material-ui/core/Card';
    import CardActions from '@material-ui/core/CardActions';
    import CardContent from '@material-ui/core/CardContent';
    // useful component for displaying text - multiple variants (body, h1, h2 etc.)
    import Typography from '@material-ui/core/Typography';
    
    export class Dashboard extends Component {
        displanyName = Dashboard.name;
    
        constructor(props) {
            super(props);
    
            this.state = {
                people: []
            };
        }
    
        componentDidMount() {
            fetch("api/people")
                .then(response => response.json())
                .then(data => this.setState({ people: data }));
        }
        render() {
            //const { people } = this.state; // equivalent to next line
            const people = this.state.people;
            if (people.length > 0)
    
            //creates an array to iterate
            let arr = people.map((person, index) => (
                <Card key={index}>
                    <CardContent>
                        <Typography variant="h5">
                            Person: {person.name}
                        </Typography>
                        <Typography variant="body2"> 
                            Job: {person.job}
                        </Typography>
                    </CardContent>
                </Card>
            ));
    
            return (
                <div>
                    {arr}
                </div>
            );
        }
    }
    

    Material UI 有很棒的文档(上面有链接)以及完整的代码示例,因此您可以准确地了解如何使用所有内容以及它如何适合您的组件。如果您像我一样对组件的 UI 外观有些困惑,我会推荐它。

    【讨论】:

      【解决方案3】:

      您的问题看起来类似于动态渲染动态组件。查看此https://gist.github.com/arifshariati/c607a2baf87976f8a2a2ce61c988db4f 进行动态渲染。

      如需完整示例,请在此处查看 React 和 Material UI 中的动态表单渲染https://github.com/arifshariati/react-dynamic-form-drag-drop-redux

      【讨论】:

        猜你喜欢
        • 2020-02-01
        • 1970-01-01
        • 2021-11-24
        • 2022-01-17
        • 2020-01-02
        • 2023-03-25
        • 2021-06-16
        相关资源
        最近更新 更多