简体   繁体   English

如何通过 React 组件传递函数

[英]how to pass functions through React components

I have a React <App> component with inside this structure:我有一个带有此结构的 React <App>组件:

{/*

INSIDE <APP>

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

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

 */}

I need a click on <Card> to activate a <Button> function, and this function should change the state of <App> as "activate" I mean that when I click on a <Card> the <Button> becomes clickable.我需要点击<Card>来激活<Button>功能,这个功能应该将<App>的状态更改为“激活”我的意思是当我点击<Card> <Button>变得可点击。

I have some problems to understand how pass function parents to children and set the state of a parent from inside a child.我有一些问题来理解如何将函数父母传递给孩子并从孩子内部设置父母的状态。 this is my App component这是我的应用程序组件

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})/>
                }

and this is the Button这是按钮

class Button extends React.Component {

    render() {
        return(

            <button   

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

                Continua

            </button>
        );
    }
}

when i click on the button i receve this error当我单击按钮时,我收到此错误

TypeError: Cannot read property 'activeIndex' of undefined类型错误:无法读取未定义的属性“activeIndex”

Use a property of the "Card" component to pass your callback function:使用“卡片”组件的属性来传递您的回调函数:

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