如何通过道具更改状态变量?

时间:2018-10-18 17:33:36

标签: react-native

我正在尝试显示带有按钮的模态屏幕,当我按下按钮时,将出现模态。负责它的变量是modalVisible及其变量状态。但是,如果我的按钮不在屏幕Profile的同一个类中,则我无法更改变量,最后我不知道该怎么做:

class Carrousel extends React.Component {
  render () {
    return (
      <Button
        title= 'press me to show up'
        onPress= {() => this.props.visible = true}
      />
    );
  }
}

export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: true,
    };
  }
  render() {
    return (
      <View>
        <Modal
         visible = {this.state.modalVisible}>
        </Modal>
        <Carrousel visible = {this.state.modalVisible}/>
      </View>
    );
  }
}

是否可以在另一个类中更改此变量modalVisible?还是有另一种方法可以让我在另一个课程中用按钮显示模式?

* carrousel类是另一个文件Carrousel.js

1 个答案:

答案 0 :(得分:1)

您必须将函数设置为prop,以更改父组件上的状态。我没有尝试过,但是应该是这样的:

class Carrousel extends React.Component {
  render () {
    return (
      <Button
        title= 'press me to show up'
        onPress= {() => this.props.setVisible()}
      />
    );
  }
}

export default class Profile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
    };
    this.setVisible = this.setVisible.bind(this);
  }

  setVisible() {
    this.setState({
      modalVisible: true,
    })
  }

  render() {
    return (
      <View>
        <Modal
         visible = {this.state.modalVisible}>
        </Modal>
        <Carrousel setVisible={this.setVisible}/>
      </View>
    );
  }
}
相关问题