react-native:如何在react上下文中更改子组件的参数?

时间:2019-05-03 23:44:30

标签: reactjs react-native react-context

我的root react-native是这样的: 我尝试使用CONTEXT API。

import { ContextProvider} from './ContextProvider';
export default class App extends React.PureComponent {
  render() {
    return (
      <ContextProvider>
        <Navigator />
      <ContextProvider>
    );
  }
}

我创建了一个像这样的简单上下文组件:

ContextProvider:

export const ParamContext = React.createContext({ param:0 });

export class ContextProvider extends React.PureComponent {
  state = {
    param: 0,
  };

  render() {
    return (
      <ContextProvider.Provider value={this.state}>
        {this.props.children}
      </ContextProvider.Provider>
    );
  }
}

我可以使用以下代码在子组件中打印param的值:

import { ParamContext } from './ContextProvider';
export default class child1 extends React.PureComponent  {
   static contextType = ParamContext;
   render(){
       console.log(this.context.param)
   }
}

有效。

现在这是我的问题。

如何在代码中使用子组件更改param

1 个答案:

答案 0 :(得分:1)

offical React documentation for Context建议除了传递值外,还传递一个函数以更改值:

// ContextProvider

export const ParamContext = React.createContext({ param:0, setParam: () => {} });

export class ContextProvider extends React.PureComponent {
    state = {
        param: 0
    }

    setParam = (param) => this.setState({ param });

    render() {
        const { setParam } = this;
        return (
            <ParamContext.Provider value={{...this.state, setParam }} >
                {this.props.children}
            </ParamContext.Provider>
        );
    }
}


// ContextConsumer
const ContextConsumer = (props) => {
    return (
        <ParamContext.Consumer>
            {({param, setParam}) => <Button onPress={() => setParam(param + 1)} title={`Current value: ${param}`} />}
        </ParamContext.Consumer>
    );
}

此示例将在每次单击按钮时将param增加1的值。