簡體   English   中英

如何使用 props 將數據從組件數組傳遞到另一個組件?

[英]How can I pass data from a component array to an another component with props?

我需要一點幫助。 我正在從事一個在 React 中使用 Class 組件的項目,但我遇到了一個問題。

如何使用道具傳遞數據

例如,假設我有一個 Component 在 state 中有一個數組:

import React,{Component} from "react";


class CarList extends Component{
  constructor(props){
  super(props);
  this.state = {
    carList: ['Jeep', 'Kwid','HB20','Ônix', 'Prisma', 'Gol quadrado']
  }
  }


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


export default CarList;

現在我必須在 Select 標簽內的選項標簽中調用此數組。

讓我們想象一下這個組件:

import React from "react";
import { Component } from "react";
import CarList from "./components/Datas";


class App extends Component{



render(){
  return(
    <div>
      <p>I got it! Here is the car list:</p>
      <select>
        {this.state.CarList.map(  (item,x)=>{
          return(
            <option key={x}>{item}</option>
          )
        })}
      </select>
    
    </div>
  )
}
}

export default App;

這段代碼不起作用。 console.log 說:“未捕獲的類型錯誤:this.state 為空”

我知道我可以用我的數據創建一個 div 並調用,但我必須使用道具在組件之間傳遞數據。

如何使用道具創建回調 function 來解決此問題?

你好!

我嘗試使用 this.state 進行調用,但出現“this.state 未定義”

要將數據作為 props 傳遞,您必須像這樣從父組件將其傳遞給子組件:

class ParentComponent extends React.Component {
  state = {
    carList: [],
  };

  constructor(props) {
    super(props);
    this.state = {
      carList: ['Jeep', 'Kwid', 'HB20', 'Ônix', 'Prisma', 'Gol quadrado'],
    };
  }

  render() {;
    return (
      <div>
        <ChildComponent carList={this.state.carList || []} />
      </div>
    );
  }
}

然后它可以在您的子組件中使用this.props

你可以像這樣在子組件中使用這個道具:

class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        {this.props.carList.map((cars, index) => {
          return (
            <span key={index}>
              {cars}
              <br />
            </span>
          );
        })}
      </div>
    );
  }
}

編輯 -

如果您想查看源代碼: https://stackblitz.com/edit/react-ts-ddcylu?file=Parent.tsx

暫無
暫無

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

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