javascript - 在 React 类中声明并重用变量?

标签 javascript reactjs

使用 React 中的纯函数,可以轻松地使您创建的任何变量都可以被任何其他嵌套函数重用:

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

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

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

  return (
    // markup
  )
}

你能用 React 类做类似的事情吗?目前我必须重复创建变量。

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
    )
  }
}

最佳答案

要在 ES6 类的函数之间共享变量,请使用成员变量。 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
    )
  }
}

请注意,您永远不应该分配或以其他方式改变任何 Prop 的值。相反,使用状态和 this.setState() 来更新内部组件状态并触发生命周期事件来更新子组件。

关于javascript - 在 React 类中声明并重用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49952265/

相关文章:

javascript - 如果/当图像加载时运行回调

go - 在 Go 中带有 child 的 React-Router 它是如何工作的?

reactjs - react-hook-form reset 不适用于 Controller + antd

javascript - VS Code 中的红色波浪线

reactjs - react 日期选择器检测月份变化?

javascript - 将变量传递给模态

javascript - 为什么 Bootstrap 3 Collapse 与双击时的复选框状态不同步?

javascript - AngularJS: Controller 中的函数被模板多次调用

javascript - 使用 HTML/Javascript 在表单文本框中显示单选按钮的值

reactjs - 有没有办法在没有样式组件的情况下为整个 react 应用程序设置默认字体系列?