【问题标题】:Why should js function's name starts with a capital letter为什么js函数的名字要以大写字母开头
【发布时间】:2020-06-04 10:03:38
【问题描述】:

我写了一个函数。我只使用简单的字母作为该函数的名称。我没有得到任何输出和错误。我突出显示了这个功能。

第三课.js

import React from 'react'

    function formattedDate(props){
    return(
    <div>This is {props.date.toLocaleTimeString()}</div>
    );
}

class Clock extends React. Component{

    constructor(props){
        super(props);
        this.state = {date:new Date()}
    }

    componentDidMount(){
        this.timerID = setInterval(() => this.tick(),1000)
    }

    componentWillUnmount(){
        clearInterval(this.timerID)
    }

    tick(){
        this.setState({
           date : new Date()
        })

    }

    render(){
        return(
            <div><h1><formattedDate date={this.state.date}/></h1></div>
        );

    }

}

export default Clock

所以我检查了我的整个代码。但是我没有发现任何错误。将函数名称更改为大写名称后,我得到了输出。请说明原因。

import React from 'react'

function FormattedDate(props){
    return(
    <div>This is {props.date.toLocaleTimeString()}</div>
    );
}

class Clock extends React.Component{

    constructor(props){
        super(props);
        this.state = {date:new Date()}
    }

    componentDidMount(){
        this.timerID = setInterval(() => this.tick(),1000)
    }

    componentWillUnmount(){
        clearInterval(this.timerID)
    }

    tick(){
        this.setState({
           date : new Date()
        })

    }

    render(){
        return(
            <div><h1><FormattedDate date={this.state.date}/></h1></div>
        );

    }

}

export default Clock

我将 Lesson3.js 导入到 App.js。除了我上面提到的错误之外,我的代码中没有错误。

App.js

import React from 'react';
import './App.css';
import Clock from './Components/lesson3'

function App() {
  return (
    <div className="App">

        <p>
          <Clock/>
        </p>

    </div>
  );
}

export default App;

【问题讨论】:

    标签: javascript


    【解决方案1】:

    在这里,您尝试将FormattedDate 用作component。不是普通函数。

    所有 React 组件名称必须以大写字母开头。如果您以小写字母开头的组件名称,它将被视为内置元素,如&lt;div&gt;&lt;span&gt;。这是因为 JSX 的工作方式。

    您可以找到更多信息here

    【讨论】:

      【解决方案2】:

      这是一种命名约定,为组件使用大写的变量/函数名称,以将它们与常规/helper/etc 函数区分开来。

      function Button() { return <button>Test</button> }
      
      function sortNumbers(array) { return ... }
      

      【讨论】:

        【解决方案3】:

        React 将以小写字母开头的组件视为 DOM 标签。 例如,&lt;div /&gt; 代表一个 HTML div 标签, 所以在:

        1. &lt;formattedDate .../&gt;React 将其视为 DOM 标签,显然不是

        另一方面,&lt;UpperCase /&gt; 代表一个组件并要求它在其范围内

        1. 因此,&lt;FormattedDate /&gt; 表示一个组件,并且要求 FormattedDate 在范围内。

        如果你想了解更多关于组件的信息,可以阅读更多at React Offical docs for component and props

        【讨论】:

          猜你喜欢
          • 2021-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-04
          • 1970-01-01
          • 2019-11-23
          • 2015-08-03
          相关资源
          最近更新 更多