没有引用的React访问组件方法

时间:2018-12-19 08:49:42

标签: reactjs

我正在尝试不使用引用来更新内部组件。
假设我有3个分量,其中A包含B,B包含C和D。
当我在A组件中触发方法时,我想更改C和D的状态。

有没有不用引用就可以做到的方法?像将孩子的事件绑定到父母一样。

2 个答案:

答案 0 :(得分:0)

是的,您可以使用下面的渲染道具来做到这一点。

您的Parent.js文件看起来像

import Mouse from './Mouse';
class App extends Component {
  render() {
    return (
      <div className="App">
        <Mouse render={({ x, y }) => (
          // The render prop gives us the state we need
          // to render whatever we want here.
          <h1>The mouse position is ({x}, {y})</h1>
        )} />
      </div>
    );
  }
}

您的孩子伴侣应该看起来像

import React, { Component } from 'react'
import PropTypes from 'prop-types';
export default class Mouse extends Component {
    static propTypes = {
        render: PropTypes.func.isRequired
      }

      state = { x: 0, y: 0 }

      handleMouseMove = (event) => {
        this.setState({
          x: event.clientX,
          y: event.clientY
        })
      }

      render() {
          console.log(this.props.render);
        return (
          <div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
            {this.props.render(this.state)}

          </div>
        )
      }
}

Demo

答案 1 :(得分:0)

You have four component A, B, C, D and you want to pass a method from A to B then B to C and D via Props. Whenever the method is call from C or D it will fire to the A component and changes some state variable. Now you want to change some state variable of C and D component by triggering that method. So basically you want to access the child state in React.

There is some suggestion How to access child state in React