React native 如何通过props更改状态变量?

React native 如何通过props更改状态变量?,react-native,React Native,我试着用一个按钮来显示一个模态屏幕,当我按下按钮时模态就会出现。负责它的变量是modalVisible,它是一个变量状态。但是,如果我的按钮与我的屏幕配置文件不在同一类中,我无法更改变量,最后我不知道该怎么做: class Carrousel extends React.Component { render () { return ( <Button title= 'press me to show up' onPress= {()

我试着用一个按钮来显示一个模态屏幕,当我按下按钮时模态就会出现。负责它的变量是
modalVisible
,它是一个变量状态。但是,如果我的按钮与我的屏幕
配置文件
不在同一类中,我无法更改变量,最后我不知道该怎么做:

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>
    );
  }
}
class Carrousel扩展了React.Component{
渲染(){
返回(
this.props.visible=true}
/>
);
}
}
导出默认类配置文件扩展React.Component{
建造师(道具){
超级(道具);
此.state={
真的,
};
}
render(){
返回(
);
}
}
有没有办法在另一个类中更改此变量
modalVisible
?或者在另一个类中有没有其他方法可以通过按钮显示模态


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

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

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>
    );
  }
}
class Carrousel扩展了React.Component{
渲染(){
返回(
this.props.setVisible()}
/>
);
}
}
导出默认类配置文件扩展React.Component{
建造师(道具){
超级(道具);
此.state={
modalVisible:错误,
};
this.setVisible=this.setVisible.bind(this);
}
setVisible(){
这是我的国家({
真的,
})
}
render(){
返回(
);
}
}