【问题标题】:components button sets state of main class react native组件按钮设置主类的状态反应本机
【发布时间】:2020-04-18 14:21:37
【问题描述】:

我的 react-native 组件 (Grid) 中有一个 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>
    );
  };
}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案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>
        );
      };
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多