首页 > 解决方案 > 如何在组件之间传输数据 - 反应?

问题描述

我在反应中有 2 个组件按钮和 lvlchecker,button.js 看起来像这样:

import React from "react";

class Button extends React.Component {
  state = {
    clickCounter: 0
  };

  handleClick = () => {
    this.setState(prevState => {
      return { clickCounter: prevState.clickCounter + 1 };
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click</button>
        <p>CLICKS: {this.state.clickCounter}</p>
      </div>
    );
  }
}

export default Button;

我想将数据从这个组件(clickCounter 函数)传输到其他组件。如何在其他组件中使用有关点击次数的信息?

标签: reactjs

解决方案


下面是一个示例,当它们作为兄弟姐妹相关时,如何Button将一些数据发送到组件,例如Info

         App
          |   
          |   
  --------|--------
  |               |
  |               |
Button          Info

代码:

 

class App extends React.Component {
  state = {
    // Now the state is duplicated because clickCounter lives both
    // inside Button and App. You could just leave the clickCounter in
    // App and remove it from Button. Then you would also pass the
    // clickCounter to Button as props as you pass it to Info.
    // This way state would not be duplicated and in general it is advised
    // in React to not duplicate state.
    clickCounter: 0
  };

  render() {
    return (
      <div>
        <Button
          clickHandler={cc => {
            this.setState({ clickCounter: cc });
          }}
        />
        <Info counter={this.state.clickCounter} />
      </div>
    );
  }
}

class Info extends React.Component {
  render() {
    return (
      <div>
        <p>Info: {this.props.counter}</p>
      </div>
    );
  }
}

class Button extends React.Component {
  state = {
    clickCounter: 0
  };

  handleClick = () => {
    this.props.clickHandler(this.state.clickCounter + 1);

    this.setState(prevState => {
      return { clickCounter: prevState.clickCounter + 1 };
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click</button>
        <p>CLICKS: {this.state.clickCounter}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


其他场景请参考这里


推荐阅读