在React中引用组件外部的变量

Reference a variable out side the component in React?

本文关键字:外部 变量 组件 引用 React      更新时间:2023-09-26

这似乎是一个愚蠢的问题,但我很好奇这是否可能(建议)。考虑以下内容:

export default class Example extends Component {
  constructor(props){
    super(props);
    this._variable = value;
  }
  render() {
    return (<div>{this.props.children}</div>);
  }
}

现在我知道我可以把this._variable传给孩子,这样:

this._childrenWithProps = React.Children.map(this.props.children,
    (child) => React.cloneElement(child, {
        variable:   this._variable,
    })
);

现在每个孩子都可以访问this.props.variable。但是(我不完全理解这个概念)我可以使用上下文或类似的东西来能够:

// In another component some where ... 
render() {
  // reference variable (this._variable, or variable) here
  <Example>
    // Children here ...
  </Example>
}

上下文是用来做这个的吗?还是我做错了什么可怕的事?实际上我想要引用这个。_variable放在元素外面,但是把它设置在元素里面。这可能吗?

是的,您可以使用上下文将变量传递给组件的所有后代,但作为一般经验法则,如果您不是绝对需要它,您应该避免使用上下文。上下文破坏了React的数据流模式,通常使代码更难阅读,因为props可能是隐式的而不是显式的。根据文档:

使用上下文将使您的代码更难理解,因为它使数据流不太清晰。这类似于使用全局变量在应用程序中传递状态。

一般来说,上下文最适合用于主题信息之类的内容,它在某些路由库中也很有用。通常有一个更好的方法来传递数据(你的cloneElementReact.Children的例子是完全好的,一个相当常见的代码片段,你会发现在很多React项目)。

如果在发出警告后仍然希望使用context,那么需要对提供上下文(通常是包装器)的组件和接收上下文的组件进行一些调整。

您的上下文提供程序需要一个getChildContext函数,该函数返回您希望对其所有子对象可用的上下文对象。您还需要将childContextTypes作为类的属性声明。

class Example extends Component {
  getChildContext() {
    return { variable: 'foo' };
  }
  render() {
    return (<div>{this.props.children}</div>);
  }
}
Example.childContextTypes = {
  variable: React.PropTypes.string
};
然后,无论您在哪里定义将作为子组件传递的组件,您希望接收上下文,您都需要添加相同的childContextTypes属性。它将通过this.context对象访问上下文。
class Child extends Component {
  render() {
    return (<div>{this.context.variable}</div>);
  }
}
Child.childContextTypes = {
  variable: React.PropTypes.string
};

childContextTypes必须的。如您所见,使用上下文并不总是意味着更少的代码。