如何传递要在其他组件中使用的特定listitem onClick的引用?

问题描述 投票:0回答:3

我有一个项目列表(用户项目),单击一个项目时,它需要重定向到一个页面,用户可以在其中编辑该单击的项目(列表项目)。

这是我目前列出项目的方式

renderingElements() {

       ...
        else {


            // Array @projectInfo : Will have objects with info from each project user currently has (title,url,genre,description)
            const projectsInfo = this.state.projectsOfUser.map(project => {
                console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^', project);
                return {

                    videoID: project._id,
                    videoTitle: project.title,
                    videoURL: project.videoURL,
                    genre: project.genre,
                    description: project.description

                }

            });

             const listItems = this.state.projectsOfUser.map((project, i) =>
                <li key={i} className="project-list-container__list__list-items" onClick={this.goToDetailComponent.bind(this)} >

                    {/* Not changing mutating in state array */}
                    {/* Passes info to each component, info is from our array of of objects with video info */}
                    <Project projectObject={projectsInfo[i]} />

                </li>
            );

            return listItems;

        }

    }

这里是列表的呈现方式

return (
            <div className="project-list-container">

                <ul className="project-list-container__list">

                    {/* If user has projects, render the list of projects */}
                    {/* {this.state.projectsOfUser && listItems} */}
                    {this.renderingElements()}

                </ul>

            </div>

        );

我的目标是能够单击列表项,在react-router上单击路由,并将单击的项目对象信息传递给我,以供我在第二个组件中使用

oToDetailComponent = () => {

        console.log('############################', someDataToPass)

        this.props.history.push(`/projectwork`) // how do i pass data of the specific project to this url/component

    };
javascript reactjs components
3个回答
0
投票

我不同意这种将数据传递到路由的方法,正确的方法应该是在路由器中设置动态路由,并使用match参数并通过调用直接从ProjectDetail组件中检索数据来自globalState的数据:

<Route path="Project/:ProjectId" />

顺便说一下,按照您的代码片段,您可以通过这种方式在推送中传递数据:

const getProjectObject = (project) => ({
  videoID: project._id,
  videoTitle: project.title,
  videoURL: project.videoURL,
  genre: project.genre,
  description: project.description
})

const renderItemList = (project) => {
  const { projectsOfUser } = this.state;
  const { history } = this.props;

  return projectsOfUser.map((project) => {
    const projectObj = getProjectObject(project);

    const navigateToProject = () => {
      history.push({
        pathname: '/projectWork',
        state: { project: projectObj }
      });
    }

    return (
      <li key={`project-${project._id}`} onClick={navigateToProject}>
        <Project project={projectObj} />
      </li>
    ) 
  })
}

在您的ProjectDetail组件中,您将能够获得您的项目:

//in case of class component
const { project } = this.props.location.state
//in case of functional component
const { project } = props.location.state

0
投票

我认为您想要这样的东西。您也可以通过这种方式将数据/对象从一个组件传递到另一组件。

<button
  onClick={() =>
    this.props.history.push("/item", {
      id: 1,
      name: "test",
      otherData: "other data"
    })
  }
>
  Save
</button>

并且您可以从location中检索所需组件中的数据

this.props.location.state

这里我只是给出了一个详细的示例,其中我只是将一些数据/对象从家庭组件传递到项目组件

home.jsx

import React, { Component } from "react";
import { Link } from "react-router-dom";
class Home extends Component {
  state = {};
  render() {
    return (
      <div>
        <h1>this is home page</h1>
        <Link to="/item">List of item</Link>
        <button
          onClick={() =>
            this.props.history.push("/item", {
              id: 1,
              name: "test",
              otherData: "other data"
            })
          }
        >
          Save
        </button>
      </div>
    );
  }
}

export default Home;

item.jsx

import React, { Component } from "react";
class Item extends Component {

  render() {
    console.log(this.props.location.state);
    return (
        <h1>
          item: {this.props.location.state.name}{" "}
          {this.props.location.state.otherData}
        </h1>
    );
  }
}

export default Item;

确保您正确维护了App.js中的路由,如下所示:>

App.js

import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./home";
import Item from "./item";

class App extends Component {

render() {
    return (
      <div>
        <Switch>
          <Route path="/item" component={Item} />
          <Route path="/" component={Home} />
        </Switch>
        </div>
    );
  }
}

export default App;

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import "./index.css";

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

serviceWorker.unregister();

我在列表项上使用箭头功能来获取单击所需的信息,在这种情况下,该信息是唯一的项目对象。 Vik的回答也很不错

   const listItems = this.state.projectsOfUser.map((project, i) =>

                <li key={i}
                    className="project-list-container__list__list-items"
                    onClick={() => this.handleClick(project)}
                >

                    {/* Not changing mutating in state array */}
                    {/* Passes info to each component, info is from our array of of objects with video info */}
                    <Project projectObject={projectsInfo[i]} />

                </li>
            );

但是,我确实看到这是一种“软的坏习惯”,并且使用子组件更为有效,因此,在确保一切正常之后,我将执行此操作。


0
投票

我在列表项上使用箭头功能来获取单击所需的信息,在这种情况下,该信息是唯一的项目对象。 Vik的回答也很不错

© www.soinside.com 2019 - 2024. All rights reserved.