【问题标题】:unexpected error create createClass with react in es6意外错误在 es6 中使用 react 创建 createClass
【发布时间】:2018-01-12 09:31:54
【问题描述】:

我在 innerFunc 中遇到了意外的令牌错误,我不知道为什么会这样。

const TestComp = () => {

  innerFunc(){ //error here?
    console.log('xx')
  }

  render() {
    return(
      <div>test comp content</div>
    )
  }
}

const Something = ({
  something
}) => {
  return(
    <div>{TestComp.toString()}</div>
  )
}

有什么线索吗?

【问题讨论】:

  • 您能否提供一些有关错误类型、错误堆栈跟踪等的信息,以便更轻松地调试您的示例?

标签: javascript reactjs ecmascript-6


【解决方案1】:

就在这里:

const TestComp = () => { // <---- Function starts

  innerFunc(){ // function inside a function needs to be declared with `function` identifer
    console.log('xx')
  }

  render() {
    return(
      <div>test comp content</div>
    )
  }
} // <---- Function ends

是一个函数。

您正在尝试向此函数添加属性,这导致了错误。

你可以像你做的那样为类添加属性。

要解决错误,请定义一个函数,如下所示:

const TestComp = () => {

  function innerFunc(){
    console.log('xx')
  }

  return( // you don't need to define render here, just return the jsx
    <div>test comp content</div>
  )
}

或者更好的是,在这个基于函数的组件之外定义它。

我希望这会有所帮助。

【讨论】:

  • 不会render() 也需要function?
  • 哦,对了!忘了那个。其实你根本不需要渲染,只需要返回 jsx。
  • 如何拨打innerFunc?在 jsx &lt;div onClick={()=&gt;this. innerFunc()} &gt;test&lt;/div&gt; 我得到了undefined的innerFunc
  • 只对onClick={innerFunc} 没有this。
【解决方案2】:

你混淆了函数式无状态组件和反应组件的语法

class TestComp extends React.Component {

  innerFunc(){ //error here?
    console.log('xx')
  }

  render() {
    return(
      <div>test comp content</div>
    )
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
相关资源
最近更新 更多