React Native:在视图层次结构中移动组件

时间:2018-05-14 18:41:25

标签: react-native

如何在保持组件状态的同时将组件从渲染层次结构的一部分移动到另一部分?在下面的示例中,调用setView的结果会创建一个新视图(如新的instanceValue数字所示),即使我传递的内容与现有视图相同。

class TestTo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      instanceValue: parseInt(Math.random() * 100)
    }
  }

  render() {
    return <Text>{this.state.instanceValue}</Text>
  }
}

class TestFrom extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      view: <TestTo />
    }
  }

  doSet = () => {
    this.props.nav.setView(this.state.view);
  }

  render() {
    return <View>
      <Button title="doaction" onPress={this.doSet} />
      {this.state.view}
    </View>
  }
}

class Holder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      view: <TestFrom nav={this} />
    }
  }

  setView = (view) => {
    this.setState({view: view});
  }

  render() {
    return this.state.view
  }
}

<Holder />

0 个答案:

没有答案