簡體   English   中英

如何通過 React 組件傳遞函數

[英]how to pass functions through React components

我有一個帶有此結構的 React <App>組件:

{/*

INSIDE <APP>

        <BreadCrumb>
                <Chip/>
                <Chip/>
                <Chip/>
                    ...
         <BreadCrumb/>

        <CardContainer>
                <Card/>  // just a clickable image 
                <Card/>
                <Card/>
                    ...
                <Button/>
        <CardContainer/>

 */}

我需要點擊<Card>來激活<Button>功能,這個功能應該將<App>的狀態更改為“激活”我的意思是當我點擊<Card> <Button>變得可點擊。

我有一些問題來理解如何將函數父母傳遞給孩子並從孩子內部設置父母的狀態。 這是我的應用程序組件

class App extends React.Component {

  constructor(props){
    super(props)
    this.state = {
      activeIndex: 1
    }

  }
    submitChoice() {   
      this.setState({activeIndex : this.state.activeIndex ++});    
    }
 }

       render() {
            return (
                 <Button onClick = {this.submitChoice})/>
                }

這是按鈕

class Button extends React.Component {

    render() {
        return(

            <button   

                onClick = {() => this.props.onClick()}
                className="button">

                Continua

            </button>
        );
    }
}

當我單擊按鈕時,我收到此錯誤

類型錯誤:無法讀取未定義的屬性“activeIndex”

使用“卡片”組件的屬性來傳遞您的回調函數:

const Card = ({ onClick, id }) => {
  const triggerClick = () => {
    onClick(id);
  };

  return (
    <div onClick={triggerClick}>Click the card</div>
  );
};

const App = () => {
 const cardClicked = id => {
   console.log(`Card with id ${id} was clicked`);
   //Modify App state here
 };

 return (
   <CardContainer>
     <Card onClick={cardClicked} id="card-1"/>
     <Card onClick={cardClicked} id="card-2"/>
   </CardContainer>
  );
}

暫無
暫無

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

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