[英]Put state from React context provider in const
我正在从我的应用程序提供程序接收状态,但是我需要在const或子组件状态下使用该状态。 但是我找不到办法。
例如,我想要这样的东西:
const admin = <MyContext.Consumer>{() =>
this.setState({username: (context =>
context.state.name)})}
</MyContext.Consumer>;
要么:
const admin = <MyContext.Consumer>{(context) => context.state.name}</MyContext.Consumer>
admin将包含状态名称的值。
我知道我的方法行不通,但是我应该采用哪种方法来做这样的事情?
<MyContext.Consumer>
只能在渲染中使用,并且它提供的值只能在传递给它的<MyContext.Consumer>
中访问。 如果您需要访问它的其他生命周期挂钩,例如用它调用setState,则有几个选项。 如果您正在使用React 16.6(我写的是最新版本),则可以使用静态contextType (请注意,它是单数的contextType,而不是contextTypes复数)
export class MyComponent extends Component {
static contextType = MyContext;
componentDidMount() {
// value is available on this.context, so you can do things like:
this.setState({ username: this.context.state.name });
}
}
在React 16.6之前,您可以将组件包装在另一个组件中,然后通过主要组件上的prop与值进行交互:
export const MyComponent = props => (
<MyContext.Consumer>
{context => <InnerComponent someExtraProp={context} {...props} />}
</MyContext.Consumer>
);
class InnerComponent extends Component {
componentDidMount() {
this.setState({
username: this.props.someExtraProp.state.name,
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.