如何指定带有功能组件的构造函数(胖箭头语法)? [英] How to specify a constructor with a functional component (fat arrow syntax)?
问题描述
给出此组件:
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
const NewGoalInput = props => {
return (
<input type="text" onKeyUp={handleKeyUp}/>
)
}
const handleKeyUp = (e) => {
if (e.key === "Enter") {
// TODO Add goal
}
}
export default NewGoalInput
如何添加无需使用extends React.Component
语法即可定义状态的构造函数?
How do I add a constructor where I can define the state without using the extends React.Component
syntax?
推荐答案
由于它是无状态组件,因此没有组件生命周期.
因此,您不能指定constructor
.
Since it's a stateless component it doesn't have the component lifecycle.
Therefor you can't specify a constructor
.
您必须扩展React.Component
来创建一个有状态组件,该组件需要一个构造函数,并且可以使用state
.
You have to extend React.Component
to create a stateful component which then will need a constructor and you'll be able to use the state
.
更新 由于反应16.8.0 和挂钩介绍了更多选项.
Update Since React 16.8.0 and Hooks got introduced there are more options.
Hooks是一项新的功能建议,使您无需编写类即可使用状态和其他React>功能.它们作为> v16.8.0的一部分在React中发布
Hooks are a new feature proposal that lets you use state and other React > features without writing a class. They are released in React as a part of > v16.8.0
无状态:
import React from "react"
const Stateless = ({name}) => (
<div>{`Hi ${name}`}</div>
);
有状态:
可以访问组件生命周期方法和本地状态.
Has access to component lifecycle methods and local state.
class Stateful extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
const { count } = this.state;
document.title = `You've clicked ${count} times.`;
}
componentDidUpdate() {
const { count } = this.state;
document.title = `You've clicked ${count} times.`;
}
render() {
const { count } = this.state;
return (
<div>
<p>You've clicked {count} times.</p>
<button onClick={() => this.setState({ count: count + 1 })}>
Click me
</button>
</div>
);
}
}
使用挂钩:
能够使用State Hook
和Effect Hook
.
如果您熟悉React类的生命周期方法,则可以将useEffect Hook视为componentDidMount,componentDidUpdate和componentWillUnmount的组合.
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
import React, { useState, useEffect } from "react";
const UsingHooks = () => {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You've clicked ${count} times.`;
});
return (
// <> is a short syntax for <React.Fragment> and can be used instead of a wrapping div
<>
<p>You've clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
这篇关于如何指定带有功能组件的构造函数(胖箭头语法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!