在Reactjs中更改父元素的状态重置所有基于<route>的组件元素的状态?

时间:2017-07-04 22:36:00

标签: javascript reactjs react-router

基本上改变<Parent />正在重置子状态。仅适用于附加到<Route />

的组件

我能够在codepen中复制问题

https://codepen.io/anon/pen/BZVdzE

var BrowserRouter =ReactRouterDOM.BrowserRouter;
var Route =ReactRouterDOM.Route;
var Link = ReactRouterDOM.Link;

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      title: "blank"
    };
  }
  changeText(x) {
    this.setState({ title: x });
  }
  render() {
    return (
      <div>
        <div className="btn" onClick={this.changeText.bind(this, 1)}>1</div>
        <div className="btn" onClick={this.changeText.bind(this, 2)}>>2</div>
        <div className="btn" onClick={this.changeText.bind(this, 3)}>>3</div>
        <p> {this.state.title}</p>
        <BrowserRouter>
        <Route path='/' component={(props) => <Child  {...props} state={this.state} />} /> 
        </ BrowserRouter>
      </div>
    );
  }
}

class Child extends React.Component {
  constructor() {
    super();
    this.state = {
      favoriteColor: "none choosen"
    };
  }
  changeColor(color) {
    this.setState({favoriteColor: color});
  }
  render() {
    return (
      <div>
        <div className="btn" onClick={this.changeColor.bind(this, 'Green')}>Green</div>
        <div className="btn" onClick={this.changeColor.bind(this, 'Purple')}>Purple</div>
        <div className="btn" onClick={this.changeColor.bind(this, 'Brown')}>Brown</div>
        <p> {this.state.favoriteColor} </p>
      </div>
    );
  }
}

ReactDOM.render(<Parent />, document.getElementById('app'));

选择喜欢的颜色,更改数字,喜欢的颜色变为默认值。

0 个答案:

没有答案