从组件B的onClick更改组件A的状态

时间:2017-05-29 21:39:05

标签: reactjs redux

我想从位于组件B中的按钮的onClick处理程序更改组件A的状态,我目前的代码如下:

组件A:

     import React, { Component } from 'react'
     import ComponentB from './component_b'
     class ComponentA extends Component{
      constructor(props){
       super(props);
        this.state=({
             allergies11:'',
             allergies12:'',
             allergies13:'',
             allergies14:''
        })
       this.onCCDSubmit = this.onCCDSubmit.bind(this);
      }
      onCCDSubmit(e){
       e.preventDefault()
       this.setState({
            allergies11:'Penicillin',
            allergies12:'2/13/10',
            allergies13:'Hives',
            allergies14:'moderate'
       })
       this.on
      }
      render(){
       return(
       <div>{this.state.allergies11}  {this.state.allergies12} {this.state.allergies13} {this.state.allergies14}
       <ComponentB />
       <div>
       )
      }
    }
    export default ComponentA;

组件B:

import React, { Component } from 'react';
class ComponentB extends Component{
 render(){
  return(
  <button type="button" onClick={this.onCCDSubmit}>Import</button>
  )
 }
}
export default ComponentB;

我怎样才能实现这一点,欢迎任何帮助!

1 个答案:

答案 0 :(得分:0)

您可以将回调传递给组件B,这会在点击后触发回调...

组件B:

import React, { Component } from 'react';
class ComponentB extends Component{
 render(){
  return(
    <button type="button" onClick={this.props.clickHandler}>Import</button>
  )
 }
}
export default ComponentB;

组件A:

 import React, { Component } from 'react'
 import ComponentB from './component_b'
 class ComponentA extends Component{
  constructor() {
    super();
    this.handleClickB = this.handleClickB.bind(this);
  }

  handleClickB(e) {
    e.stopPropagation();
    this.setState({
      // new state you want to set...
    });
  }

  render(){
   return(
   <div>{this.state.allergies11}  {this.state.allergies12} {this.state.allergies13} {this.state.allergies14}
   <ComponentB clickHandler={this.handleClickB} />
   <div>
   )
  }
}
export default ComponentA;