【问题标题】:How to pass props to components in React js如何在 React js 中将 props 传递给组件
【发布时间】:2021-05-06 18:09:38
【问题描述】:

我正在使用 React JS 开发一个项目,我想将一个道具传递给一个数组, 这是组件:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class TaskItem extends Component {
  
  render() {
    const task = this.props.task;

    return (
        <tr>
          <Link to={`/tasks/${task.id}`}>
                {task.name}
          </Link>
        </tr>
    );
  }
}

export default TaskItem;

我希望{task.name} 的值出现在这个数组的标题中:

const todoDB = {
    todos  : [
        {
        //Proident tempor est nulla irure ad est
            'id'       : '561551bd7fe2ff461101c192',
            'title'    : ' ===> HERE <===' ,
            'notes'    : 'Id nulla nulla proident deserunt deserunt proident in quis. Cillum reprehenderit labore id anim laborum.',
            'startDate': new Date(2018, 8, 3),
            'dueDate'  : new Date(2018, 8, 5),
            'completed': false,
            'starred'  : false,
            'important': false,
            'deleted'  : false,
            'labels'   : [1]
        }
]

数组和组件不在同一个文件中 我希望这些信息足以理解我的问题,谢谢

【问题讨论】:

  • 您是在寻找一种从 json 数组中读取的方法,还是尝试将其存储在数组中?
  • 我正在尝试将task.name 的值存储在数组中

标签: javascript arrays reactjs components


【解决方案1】:

您可以将 todoDB.todos 数组转换为函数,将 prop 传递给函数并调用它。像下面这样的:

const todoDB = {
  todos: (props) => [{
    'id': '561551bd7fe2ff461101c192',
    'title': props,
    'notes': 'Id nulla nulla proident deserunt deserunt proident in quis. Cillum reprehenderit labore id anim laborum.',
    'startDate': new Date(2018, 8, 3),
    'dueDate': new Date(2018, 8, 5),
    'completed': false,
    'starred': false,
    'important': false,
    'deleted': false,
    'labels': [1]
  }]
}
console.log(todoDB.todos("this is the title")[0].title)

【讨论】:

    【解决方案2】:

    我对您的要求并不完全清楚,但以下是一个可以按照您提供的格式生成任务数组的函数。

    const generateTodoDB = todos => ({
        todos: todos.map(todo => ({
            'id'       : '561551bd7fe2ff461101c192',
            'title'    : todo.title,
            'notes'    : 'Id nulla ...',
            'startDate': new Date(2018, 8, 3),
            'dueDate'  : new Date(2018, 8, 5),
            'completed': false,
            'starred'  : false,
            'important': false,
            'deleted'  : false,
            'labels'   : [1]
        })
    })
    

    现在您只需调用 generateTodoDB 函数,传入一个待办事项数组。

    const myTodos = [{ title: "Get Milk" }, { title: "Get Bananas" }];
    const todoDB = generateTodoDB(myTodos);
    

    generateTodoDB 是一个所谓的箭头函数。它会自动返回其函数的结果,因为它的主体被包裹在括号中。 todos.map 也是如此。

    const fn1 = () => ({ thisObject: "gets returned" })
    const fn2 = () => { return { thisObjectDoes: "not return automatically" } }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2015-07-12
      • 2017-09-14
      • 2017-02-13
      • 1970-01-01
      • 2020-06-12
      相关资源
      最近更新 更多