组件按钮设置主类的状态反应本机

时间:2020-04-18 14:21:37

标签: javascript reactjs react-native

我的本​​机组件(网格)中有一个TouchableOpacity按钮,我需要更改调用该组件(App.js)的类的状态。这可能吗?

App.js

import Grid from '../components/Grid'

export default class App extends React.Component {
  state = {
      opt: '1'
  }

  render(){
    return(
      <View style={styles.container}>
        <Grid/>
      </View>
    );
  };
}

Grid.js

export default class Grid extends React.Component {
  _setMainState = () => {
    this.setState({
      opt:'2'
    });
  }

  render(){
    return(
      <View style={styles.container}>
         <TouchableOpacity onPress={this._displayList}>
            <Text>Set App.js State</Text>
         </TouchableOpacity>
      </View>
    );
  };
}

1 个答案:

答案 0 :(得分:1)

您可以将状态设置器传递给子组件,尽管这不是最佳做法,因为它可能会导致无限的重新渲染循环。
尝试使用上下文,或将您的元素包装在另一个存储此值的元素中。

import Grid from '../components/Grid'

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      opt: '1'
    };
  }
  
  changeOpt(newOpt) {
    this.setState({
      opt: newOpt,
    });
  }

  render() {
    return(
      <View style={styles.container} changeOpt={this.changeOpt.bind(this)}>
        <Grid/>
      </View>
    );
  };
}