簡體   English   中英

將 prop 傳遞給另一個組件並在視圖上呈現

[英]Passing prop to another component and render on the view

import Form from './Form'
  class SideBar extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
    item: '' 
  };
}
render() {
  return (
    this.props.products.map((x) => {
    let boundItemClick = this.onItemClick.bind(this, x);
    return <li key={x.id} onClick={boundItemClick}>{x.id}-{x.style_no}-{x.color}</li>

    }));
  }

  onItemClick= function(item, e) {  
    console.log(item)
  }
 }

export default SideBar
import SideBar from './SideBar'

class Form extends React.Component{
  render(){

  return();

}
}


 export default Form




**strong text**<div class = first_half><%= react_component("SideBar", {products: 
@products}) %></div>
<div class = second_half><%= react_component("Form", {products: 
@products}) %></div>

我有一個關於如何將道具傳遞給 Form 組件的問題。 眼下,SideBar 組件列出了所有的鏈接,所有我點擊的鏈接之一,我都可以通過 console.log 記錄信息。 但我不知道如何將它傳遞給另一個組件並在視圖上呈現。 謝謝

例如:(這是一個側邊欄組件)301-abc 302-efg 303-rgk

當用戶點擊 301-abc 時,它將顯示相應的詳細信息,如 id、顏色和樣式。

同樣SideBar組件,您必須創建構造函數一個Form組件。

並且您必須使用產品詳細信息創建狀態

class SideBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      item: ''
    };
  }
  render() {
    return (
      this.props.products.map((x) => {
        let boundItemClick = this.onItemClick.bind(this, x);
        return <li key={x.id} onClick={boundItemClick}>{x.id} - {x.style_no} - {x.color}</li>
      }));
  }

  onItemClick = function(item, e) {
    console.log(item)
    this.props.selectedData(item);
  }
}
export default SideBar

import SideBar from './SideBar'

class Form extends React.Component {
  constructor() {
    this.state = {
      products: [{
        id: '302',
        style_no: 'abc',
        color: 'red'
      }, {
        id: '303',
        style_no: 'abcd',
        color: 'black'
      }],
      selectedData: {}
    };
  }

  getSelectedData(selectedData) {
    this.setState({
      selectedData: selectedData
    });
  }

  render() {
    return ( 
      <SideBar products = {this.state.products} selectedData={this.getSelectedData}>
    );
  }

}

在上面的代碼中,我有 pass 方法作為 pops,名稱為selectedData ,你可以在你的onItemclick方法中使用它,因為我使用它並傳遞你的項目。

this.props.selectedData(item);

因此,您將在Form組件中獲取該項目並設置您的狀態,您可以在Form組件中顯示它,也可以將其傳遞給另一個組件。

希望它對你有用..!!

如果您有很多需要了解彼此狀態/信息的嵌套組件,那么您最好的選擇是選擇一種狀態管理,例如reduxflux等。狀態管理的任務是跨組件保存數據並幫助您保持反應中的單向數據流。 雖然,如果您出於任何原因不想使用狀態管理機制。 你可以像這樣實現它(這很丑陋): https : //stackblitz.com/edit/react-pkn3cu

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM