2017-09-08 51 views
-1

我需要將其從功能組件轉換爲類組件,以便我可以利用React.Component的componentDidMount方法。在將React函數組件轉換爲類組件時遇到問題

const receivedStyle = { 
    marginRight: '0', 
    marginLeft: 'auto', 
}; 
const receivedBubble = { 
    backgroundColor: '#709AFF', 
    color: 'white', 
}; 
const receivedDate = { 
    marginRight: '0', 
    marginLeft: 'auto', 
}; 

const MessageBubble = ({ message, received }) => (
    <div className="message-bubble" style={received ? receivedStyle : null}> 
    <div className="bubble" style={received ? receivedBubble: null}> 
     {message.message} 
    </div> 
    <span className="date" style={received ? receivedDate: null}>{Moment(message.timestamp).startOf('minute').fromNow()}</span> 
    </div> 
); 

export default MessageBubble; 
+1

有什麼問題?只需將ui部分放在render方法中並使用'this.props'來訪問道具值。檢查文檔[**如何將功能組件轉換爲類組件**](https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components) –

回答

0

我不明白是什麼問題。無論如何,這裏是:

import React, { Component } from 'react' 

const receivedStyle = { 
    marginRight: '0', 
    marginLeft: 'auto', 
} 

const receivedBubble = { 
    backgroundColor: '#709AFF', 
    color: 'white', 
} 

const receivedDate = { 
    marginRight: '0', 
    marginLeft: 'auto', 
} 

export default class MessageBubble extends Component { 
    componentDidMount() { 
    ... 
    } 

    render() { 
    const { message, received } = this.props 

    return (
     <div className="message-bubble" style={received ? receivedStyle : null}> 
     <div className="bubble" style={received ? receivedBubble: null}> 
      {message.message} 
     </div> 
     <span 
      className="date" 
      style={received ? receivedDate: null} 
     > 
      {Moment(message.timestamp).startOf('minute').fromNow()} 
     </span> 
     </div> 
    ) 
    } 
} 
+2

它甚至不是那麼簡單,你錯過了'class'關鍵字,並忘記提及如何導入組件。 –

+0

你得到它:) – mersocarlin

+0

我應該在哪裏寫receivedStyle,receivedBubble和receivedDate的代碼? –

相關問題