2017-05-30 86 views
1

鑑於此組件:如何使用功能組件(胖箭頭語法)指定構造函數?

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語法?

+2

功能組件沒有生命週期的工作流的執行,儘管他們沒有的狀態。如果你想使用狀態,你必須從'React.Component'擴展 – Ematipico

回答

3

由於它是無狀態組件,因此它沒有組件生命週期。 因此,您無法指定constructor

你必須擴展React.Component來創建一個有狀態的組件,然後需要一個構造函數,你就可以使用state

無狀態:

var React = require('react'); 

const Stateless = ({name}) => (
    <div>{`Hi ${name}`}</div> 
); 

有狀態:

class Stateful extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = {data: "Stateful"}; 
    } 

    render() { 
    return (
     <div> 
     <h1>Hello, world!</h1> 
     <h2>It is {this.state.data}.</h2> 
     </div> 
    ); 
    } 
} 
2

你不知道。您示例中的組件類型稱爲「無狀態功能組件」。它沒有狀態和沒有生命週期方法。如果你希望你的組件是有狀態的,你將不得不把它寫成一個類組件。