【问题标题】:Wrapping a third party lib包装第三方库
【发布时间】:2017-12-22 19:29:49
【问题描述】:

让我将问题简化为以下人工案例:

Child 是 Parent 的子组件,使用如下:

<Parent>
   <Child parentColor=32/>
</Parent>

现在,Child需要设置Parent的颜色。

基本上,我应该在哪里/如何处理 Child 需要访问 Parent 的 DOM 元素的情况。

【问题讨论】:

  • 利用全局应用程序状态可能是一种解决方案。像 Redux 或类似的商店,其中一些操作可以改变 Parent 的状态。

标签: reactjs


【解决方案1】:

react 中的数据流是单向流,从 Parent 到 Child。
孩子通常会通过回调(或事件处理程序)将数据传回给父母。

子组件不应该知道它的父母或兄弟姐妹,它应该只关心它自己,在某些情况下它应该关心它自己的孩子。

例如,具有文本输入和按钮的 Child。它将以自己的状态管理输入的值,并通过其按钮的onClick 事件将其输入的值传回。

父母会如何处理这个值? Child 组件并不关心。处理程序事件通过父级传递给它,子级将使用其状态中的值调用它。这就是孩子需要知道的全部内容。

这是一个运行中的小例子:

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
  }

  onChange = ({ target }) => {
    this.setState({ value: target.value });
  }

  onSubmit = () => {
    const { onSubmit } = this.props;
    onSubmit(this.state.value);
  }

  render() {
    const { value } = this.state;
    return (
      <div>
        <input
          placeholder="type a color"
          type="text"
          value={value}
          onChange={this.onChange}
        />
        <button onClick={this.onSubmit}>Change Color</button>
      </div>
    );
  }
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: 'green'
    };
  }

  onColorChange = color => this.setState({ color });

  render() {
    const { color } = this.state;
    return (
      <div style={{ backgroundColor: color }}>
        <Child onSubmit={this.onColorChange} />
      </div>
    );
  }
}

ReactDOM.render(<Parent />, document.getElementById("root"));
<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>
<div id="root"></div>

【讨论】:

  • 我写道这是一个人为的案例。原因是第三方库在 DOM 之外有自己的对象模型。
  • 我假设第三方组件是您的情况下的子组件。那么如果它有一个通过回调提供数据的api,那么问题出在哪里?或许提供您正在使用的真实用例和第三方组件?
猜你喜欢
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
相关资源
最近更新 更多