react + redux儿子组件如何获得道具?

时间:2016-10-17 06:29:52

标签: reactjs redux react-redux

这是我的代码:
动作:
const increaseAction = { type: 'increase' }
reducer:

  // Reducer
  function counter(state = { count: 0 }, action) {
    const count = state.count
    switch (action.type) {
    ┊ case 'increase':
    ┊ ┊ return { count: count + 1 }
    ┊ default:
    ┊ ┊ return state
    }
  }

这是我的商店:
const store = createStore(counter)
和其他人:

  // Map Redux state to component props
  function mapStateToProps(state) {
    console.log(33333);
    return {
    ┊ value: state.count
    }
  }

  // Map Redux actions to component props
  function mapDispatchToProps(dispatch) {
    return {
    ┊ onIncreaseClick: () => {
    ┊ ┊ console.log(22222222222);
    ┊ ┊ dispatch(increaseAction)
    ┊ }
    }
  }

  // Connected Component
  const App = connect(
    mapStateToProps,
    mapDispatchToProps
  )(Main)


  ReactDOM.render(
    ┊ <Provider store={store}>
    ┊ ┊ <App />
    ┊ </Provider>,
    document.getElementById('content')
  );

**我的主要成分:**

>>class Main extends React.Component {
    constructor(props) {
    ┊ super(props);
    }
    render() {
      const {value, onIncreaseClick} = this.props;
    ┊ return (
    ┊ ┊ <div className={reactRootClass}>
    ┊ ┊ ┊ <div className='trade-left' onClick={onIncreaseClick}>
    ┊ ┊ ┊ </div>
    ┊ ┊ ┊ <div className='trade-right'>
    ┊ ┊ ┊ ┊ <Counter />
    ┊ ┊ ┊ </div>
    ┊ ┊ </div>
    ┊ )
    }
  }

这是我的问题:
现在,我可以在onIncreaseClick

上致电<div className='trade-left' onClick={onIncreaseClick}>

现在我想在onIncreaseClick组件中调用<Counter />,如何在value组件中获得onIncreaseClick<Main>?与props
这是我的<Counter>组件:

>>import React, { Component, PropTypes } from 'react'
  export default class Counter extends Component {
    render() {
    ┊ const { value, onIncreaseClick } = this.props
    ┊ return (
    ┊ ┊ <div>
    ┊ ┊ ┊ <span>{value}</span>
    ┊ ┊ ┊ <button onClick={onIncreaseClick}>Increase</button>
    ┊ ┊ </div>
    ┊ )
    }
  }

我只想在此

中致电onIncreaseClick

1 个答案:

答案 0 :(得分:0)

你可以通过MapStateToProps方法传递状态(给孩子们),同样你也可以通过mapDispatchToProps函数传递给孩子的动作,如下所示:

function mapDispatchToProps(dispatch) {
  const {updateData} = importedActions;
  return {
    actions: bindActionCreators({updateData}, dispatch),
  };
}

这就是容器与层次结构中所有子组件进行通信的方式