反应:发送功能作为道具

时间:2020-04-15 10:56:10

标签: reactjs

我有一个主要的App组件,其中有2个状态变量和2个按钮单击处理程序功能,这些单击处理程序会更新App的状态。 App内还有一个PageLoader组件,我想发送给PageLoader(App的功能和状态变量)。 我想通过两个在PageLoader中的按钮来触发App的功能。

App.js

import React from 'react';
import PageLoader from './Components/PageLoader';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loadComponent1: false,
      loadComponent2: false
    }
  }
  handleButton1 = () => {
    this.setState(state => ({ loadComponent2: !state.loadComponent2 }));
  }
  handleButton2 = () => {
    this.setState(state => ({ loadComponent2: !state.loadComponent2 }));
  }
  render() { 
    return ( 
      <PageLoader 
        loadComponent1={this.state.loadComponent1}
        loadComponent2={this.state.loadComponent2}
        handleButton1={this.handleButton1}
        handleButton2={this.handleButton2}
      />
    );
  }
}

export default App;

PageLoader.js

import React from 'react';
import Component1 from './Component1';
import Component2 from './Component2';

export default function PageLoader() {

    this.props.handleButton1 = this.props.handleButton1.bind(this);
    this.props.handleButton2 = this.props.handleButton2.bind(this);

    const Component1Button = ({ onClick }) => (
        <button onClick={onClick} type="button">Load Component 1</button>
    )
    const Component2Button = ({ onClick }) => (
        <button onClick={onClick} type="button">Load Component 2</button>
    )
    const Page = ({ loadComponent1, loadComponent2 }) => 
    loadComponent1 ? <Component1/> : loadComponent2 ? <Component2/> : <div>NOT 
    LOADED</div>;

    return(
        <main>
            <Page/>
            <Component1Button onClick={this.props.handleButton1}/>
            <Component2Button onClick={this.props.handleButton2}/>
        </main>
    )  
}
THANK YOU

1 个答案:

答案 0 :(得分:0)

按如下所示更改PageLoader

export default function PageLoader(props) {
  const handleButton1 = props.handleButton1;
  const handleButton2 = props.handleButton2;

页面和ComponentButtons应该像这样

 <main>
      <Page
        loadComponent1={props.loadComponent1}
        loadComponent2={props.loadComponent2}
      />
      <Component1Button onClick={handleButton1} />
      <Component2Button onClick={handleButton2} />
  </main>