简体   繁体   English

在React类中声明和重用变量?

[英]Declare and reuse variable in a React Class?

With pure functions in React it's easy to make any variable you create reusable by any other nested functions: 使用React中的纯函数,可以很容易地使您创建的任何变量可被任何其他嵌套函数重用:

const myComponent = props => {
  const {something} = props.nested;

  const nestedFunction = () => {
    if (something === "value") return true
  }

  const otherNestedFunction = () => {
    console.log(otherNestedFunction)
  }

  return (
    // markup
  )
}

Can you do something similar with a React class? 你可以对React类做类似的事情吗? At the moment Im having to repeat creating the variable. 目前,我必须重复创建变量。

class myComponent extends React.Component() {

  nestedFunction() {
    const {something} = props.nested;
    if (something === "value") return true
  }

  otherNestedFunction() {
    const {something} = props.nested;
    console.log(otherNestedFunction)
  }

  render(){
    return (
      // markup
    )
  }
}

To share variables among functions of an ES6 class, use member variables. 要在ES6类的函数之间共享变量,请使用成员变量。 React provides props as a member variable which you can access with this.props : React提供了props作为成员变量,您可以使用this.props进行访问:

class myComponent extends React.Component() {

  nestedFunction() {
    if (this.props.nested === "value") return true
  }

  otherNestedFunction() {
    console.log(this.props.nested)
  }

  render(){
    return (
      // markup
    )
  }
}

Note that you should never assign or otherwise chance the value of any props. 请注意,切勿分配或分配任何道具的价值。 Instead, use state with this.setState() to update internal component state and trigger lifecycle events to update children components. 而是将state与this.setState()一起使用以更新内部组件状态并触发生命周期事件以更新子组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM