【问题标题】:Update parent React component from child component从子组件更新父 React 组件
【发布时间】:2019-03-11 13:45:01
【问题描述】:

我正在使用 react context api 在任何地方显示我的数据,并从我想要的任何地方进行更新,以便我的数据可以显示在多个屏幕上,并且我可以从多个类进行更新,我需要在全局范围内使用它。

当我尝试从班级资料屏幕更新它时,什么也没有发生,但它可以从班级主屏幕更新。

如何在不使用这种方式的情况下在消费者中显示我的数据,并在全球范围内显示此数据

const Context = React.createContext("default value")    
global.cart = 1;

作为上下文提供者类的类主屏幕

class HomeScreen extends Component<Props> {
    constructor(props){
      super(props);
      this.state={
          contextData:5}}
  render() {
    return (
      <View>
      <Context.Provider value={this.state.contextData}>
        <Button title="Increment" onPress={++global.cart;
        this.setState({contextData:global.cart})}/>
      </Context.Provider>
      <ProfileScreens/>
      </View>
    )
  }
}

我需要在许多屏幕中使用和显示的文本

class ProfileScreen extends Component<Props> {
  render() {
  return (
      <View style={{}}>
        <Context.Consumer>
          {data=>  <Text style={{fontSize:50}}>{data.toString()}</Text>}
        </Context.Consumer>
      </View>
    );
  }
}

另一个改变上下文提供者数据的类

class ProfileScreens extends Component<Props> {
  constructor(props){
    super(props);
    this.state={contextData:5}}
  render() {
    return (
      <View >
        <Context.Provider value={this.state.contextData}>
          <ProfileScreen/>
          <Button title="decrementss" onPress={()=>{  ++global.cart;
            this.setState({contextData:global.cart})}}/>
        </Context.Provider>
      </View>
    );
  }
}

【问题讨论】:

    标签: reactjs react-native react-native-android react-native-ios react-context


    【解决方案1】:

    您需要将回调从HomeScreen 向下传递到ProfileScreens 此回调将在ProfileScreens 内调用并触发HomeScreen 状态更改:

    HomeScreen:

    ...
    <ProfileScreens changeHomeScreen={() => this.setState({...})}/>
    ...
    

    然后在ProfileScreens:

    ...
    <Button title="decrementss" onPress={()=>{ this.props.changeHomeScreen() }}/>
    ...
    

    【讨论】:

    • 如何在不使用这样的情况下在消费者中显示我的数据,并在全球范围内显示此数据
    猜你喜欢
    • 1970-01-01
    • 2023-02-20
    • 2020-05-31
    • 2018-10-09
    • 2020-08-08
    • 1970-01-01
    • 2022-01-07
    • 2021-04-02
    • 2018-07-20
    相关资源
    最近更新 更多