【问题标题】:hooks are not rendering in react钩子没有在反应中呈现
【发布时间】:2019-07-01 05:59:27
【问题描述】:

在反应中,我正在尝试使用反应钩子。我创建了一个包含表单的钩子,并将其导入基于类的组件中并在那里呈现。但是钩子没有在接触组件中呈现

//contactushook.js

import React from 'react';
const contactUshook = props => {
    return <React.Fragment>
        <form>
            <div>
                <input id="name" type="text" placeholder="enter the     name"></input>
            </div>
            <div>
                <input id="email" type="email" placeholder="enter the email"></input>
            </div>
            <div>
                <input id="message" type="text-area" placeholder="Type message here"></input>
            </div>
            <button type="submit">Submit</button>
        </form>
    </React.Fragment>

}
export default contactUshook;

//contact.js

import React, { Component } from 'react';
import contactUshook from './hooks/contactushook';
class ContactComponent extends Component {

    render() {
        return (
            <div>
                <h4>hook</h4>
                <contactUshook></contactUshook>
            </div>
        );
    }
}

export default ContactComponent;

【问题讨论】:

  • contactUshook 不是钩子,它只是一个功能组件。如果你想使用它,那么在渲染中使用import ContactUs from '...'&lt;ContactUs /&gt;。 React 组件应该以大写字母开头。并且您不需要组件的打开和关闭标签。同样在contactUshook 你不需要片段。当你有两个没有根的兄弟元素时,片段就在那里。
  • contactUs 不是钩子,只是一个函数组件,它们应该以大写字母开头,否则不会渲染。

标签: reactjs react-hooks react-component


【解决方案1】:

您的代码运行良好。您应该将自定义组件命名为 &lt;contactUshook&gt;,以 capital letter 开头,这样 React 就知道它是自定义组件而不是 html 标签。

注意:组件名称始终以大写字母开头。

React 将以小写字母开头的组件视为 DOM 标签。例如,表示一个 HTML div 标签,但表示一个组件,并且需要 Welcome 在范围内。

所以这会解决你的问题

import React, { Component } from 'react';
import ContactUshook from './hooks/contactushook';
class ContactComponent extends Component {

    render() {
        return (
            <div>
                <h4>hook</h4>
                <ContactUshook></ContactUshook>
            </div>
        );
    }
}

export default ContactComponent;

如前所述,您的代码不处理钩子。您创建了普通组件。

工作样本是here

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 2020-03-25
    • 1970-01-01
    • 2021-12-04
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多