开发者问题收集

hooks 未在 React 中呈现

2019-07-01
111

在 React 中,我尝试使用 React Hooks。我创建了一个包含表单的 Hook,并将其导入基于类的组件中并在那里进行渲染。但 Hooks 未在联系人组件中进行渲染

//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;
1个回答

您的代码运行良好。您应该将自定义组件命名为 <contactUshook> ,并以 大写字母 开头,这样 React 就知道它是自定义组件,而不是 html 标签。

Note: Always start component names with a capital letter.

React treats components starting with lowercase letters as DOM tags. For example, represents an HTML div tag, but represents a component and requires Welcome to be in scope.

因此这将解决您的问题

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;

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

工作示例位于 此处

Fyodor Yemelyanenko
2019-07-01