如何将 json 数据对象 {items.symbol} 值传递给另一个 class

How to pass json data object {items.symbol} value to another class

我正在使用 React js。我有一个 class Stock.js,我正在其中获取 api 并以 table 的形式在网页上显示数据。 当我点击 table 数据时(table 数据是链接)它发送 item.symbolonhandleclick() 方法。例如:

    |Symbol|Age|
     |X  | 20|
     |Y  |22 |

因此符号 table 中的值被称为 item.symbol 在这里,如果我单击 X,它会将值 X 发送到 onhandleclick(),现在我想将此值 XY 发送给另一个用户单击的值class。另一个 class 我的意思是说我有一个 class xyz.js 我想将 item.symbol 的值发送到 class xyz.js 所以我可以使用这个值,然后在我的 xyz.js class 中用那个值做任何我想做的事。有办法吗?

我的代码:(Stock.js)

import React, { Component } from "react";
import { Link } from "react-router-dom";
import Symbols from "./Symbols";

export default class Stocks extends Component {


  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
     symbolsname: "",
    };
  }


  handleClick(symbol) {
      //pass the value to another class here
  }

  componentDidMount(symbol) {
    fetch("http://131.181.190.87:3001/all")
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          isLoaded: true,
          items: json,

        });
      });
  }

  render() {

    let filteredItems = this.state.items.filter((item) => {
      return (
        item.symbol.toUpperCase().indexOf(this.state.search.toUpperCase()) !==
          -1 || item.industry.indexOf(this.state.search) !== -1
      );
    });
    var { isLoaded, items } = this.state;
    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>

          <table border={2} cellPadding={1}>
            <thead>
              <tr>
                <th>Symbol</th>
                <th>Name</th>
                <th>Industry</th>
              </tr>
            </thead>

            <tbody>
              {filteredItems.map((item) => (
                <tr>
                  <Link to="/symbols">
                    <td
                      key={item.symbol}
                      onClick={() => this.onhandleclick(item.symbol)} //here I am passing the value of item.symbol to onhandleclick()
                    >
                      {item.symbol}
                    </td>
                  </Link>

                  <td key={item.name}>{item.name}</td>
                  <td key={item.industry}>{item.industry}</td>
                </tr>
              ))}
              }
            </tbody>
          </table>
        </div>
      );
    }
  }
}

做了maniraj-murugan回答里说的后,上面写着undefined,所以我上传了截图

您可以从 Symbol.js 导出函数并在 handleClick 中使用它。

// Symbol.js
export default class Symbol {
  doSomething(symbol) {
    // do something
  }
}
// Stocks.js
import Symbol from 'Symbol.js';

handleClick(symbol) {
  Symbol.doSomething(symbol);
};

您可以使用 history.push 和点击事件处理程序重定向到 symbol.js,例如,(在此处删除 Link 标记)所以更改,

    <Link to="/symbols">
      <td key={item.symbol} onClick={() => this.onhandleclick(item.symbol)} //here I am passing the value of item.symbol to onhandleclick()>
            {item.symbol}
      </td>
   </Link>

到,

<td key={0} onClick={() => this.onhandleclick(item.symbol)} 
style={{ cursor: "pointer", color: "blue" }}
 >
   {item.symbol}
</td>

onHandleClick功能类似,

onhandleclick(data) {
    const { history } = this.props;
    history.push({
      pathname: "/Symbol",
      symbol: data
    });
  }

这里第二个 属性 是你可以传递的道具,在你的情况下它是符号,所以你可以像 symbol: data ..

Working Sandbox: https://codesandbox.io/s/react-router-v4-withrouter-demo-2luvr

更新: -> 从 OP 更新后,已经做了一些更改。

=> import { BrowserRouter } from "react-router-dom"; in the main component index.js where you are initializing the parent component in the call to ReactDOM.render .

index.js:

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";
import { BrowserRouter } from "react-router-dom";

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

stocks.js:

import React, { Component } from "react";
import { Link } from "react-router-dom";
import Symbols from "./Symbols";

const filteredItems = [
  { symbol: "X", name: "item1", industry: "industry1" },
  { symbol: "Y", name: "item2", industry: "industry2" }
];

export default class Stocks extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
      search: "",
      symbol: ""
    };
  }

  updateSearch(event) {
    this.setState({ search: event.target.value });
  }

  onhandleclick(data) {
    const { history } = this.props;
    history.push({
      pathname: "/Symbols",
      symbol: data
    });
  }

  componentDidMount() {}

  render() {
    return (
      <div>
        <form className="form-for-table-search">
          Search symbol or industry: &emsp;
          <input
            type="text"
            value={this.state.search}
            onChange={this.updateSearch.bind(this)}
          />
          &emsp; &emsp;{" "}
          <button type="button" className="btn-submit">
            Search
          </button>
          <br />
        </form>
        <table border={2} cellPadding={1}>
          <thead>
            <tr>
              <th>Symbol</th>
              <th>Name</th>
              <th>Industry</th>
            </tr>
          </thead>

          <tbody>
            {filteredItems.map((item, index) => (
              <tr key={index}>
                <td
                  key={0}
                  onClick={() => this.onhandleclick(item.symbol)} //here I am passing the value of item.symbol to onhandleclick()
                  style={{ cursor: "pointer", color: "blue" }}
                >
                  {item.symbol}
                </td>

                <td key={item.name}>{item.name}</td>
                <td key={item.industry}>{item.industry}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

Symbols.js:

import React from "react";

export default class Symbol extends React.Component {
  componentDidMount() {
    console.log("came here", this.props.location.symbol);
  }

  render() {
    return <div>Symbol value: {this.props.location.symbol}</div>;
  }
}

Updated Sandbox