0

親は setState Triggersrender()ですが、子コンポーネントの小道具は静的です

これはかなり簡単です。私は<Parent />状態プロパティとハンドラーを持っています。親は、プロパティとハンドラーの両方を子に渡します。

子にはボタンがあり、親のハンドラーをラップする独自のハンドラーを呼び出します。ブール値 ,isNewが Parent に渡されます -- 親呼び出しthis.setState({ isNew: isNew }).

親は常に呼び出し、親の HTMLrenderで出力するとisNew、すべてが正しいことが示されます。ただし、<Child isNew={this.state.isNew} />から正しい値を出力することはありません。常に、親のメソッドthis.props.isNew内の親で初期化される値です。getInitialProps

私はこのプロジェクトに参加したばかりですが、Flux や Redux を実装しているとは思えません。私の仮定では、React はすぐに使える状態で、props が親の state に設定されているすべての子を再レンダリングする必要があるというものでした。

言い換えれば、次のものがあれば:

React.createClass({
    render: function () {
        return (<Child isNew={this.state.isNew} handler={this.handler} />);
    }
});

親が [状態変更から] 再レンダリングする場合、親の状態に依存するすべての子も、親の新しい状態を小道具にカプセル化しながら再レンダリングする必要があります。の子小道具を想定<Child property={this.state.property} />

ここで基本的なものが完全に欠けていますか?

これについて私をまっすぐにしてください:)

どうも

4

1 に答える 1

0

this.props.isNew を子コンストラクターに設定して、印刷しようとすると思います..

孫:

import React, { Component } from 'react';

class GrandChild extends Component {
  constructor(props) {
    super(props);
    this.toogle = this.toogle.bind(this);
  }

  toogle(e) {
    if (e) {
      e.preventDefault();
    }
    this.props.toogleParent(!this.props.isNew);
  }

  render() {
    console.log('in grand child', this.props.isNew);
    return (
      <div>
        <a onClick={this.toogle} href="">click</a>
      </div>
    );
  }
}

export default GrandChild;

子コンポーネント:

import React, { Component } from 'react';
import GrandChild from './grand';


class Child extends Component {
  render() {
    console.log('in child', this.props.isNew);
    return (
      <div>
        <GrandChild {...this.props} />
      </div>
    );
  }
}

export default Child;

親コンポーネント:

import React, { Component } from 'react';
import Child from './child';

class MainPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isNew: false
    };
    this.toogleParent = this.toogleParent.bind(this);
  }

  toogleParent(isNew) {
    this.setState({ isNew });
  }

  render() {
    console.log('in parent', this.state.isNew);
    return (
      <div>
        <h3>Main page</h3>
        <Child isNew={this.state.isNew} toogleParent={this.toogleParent} />
      </div>
    );
  }
}

export default MainPage;

出力:

親で true 子で true 孫で true

親で false 子で false 孫で false

等..

于 2016-05-20T17:43:50.937 に答える